Home > Web Front-end > JS Tutorial > body text

How to Trace Caller Function Details (Line Number and Source URL) in JavaScript?

Barbara Streisand
Release: 2024-10-20 21:53:30
Original
829 people have browsed it

How to Trace Caller Function Details (Line Number and Source URL) in JavaScript?

Tracing Caller Details in JavaScript: Line Number and Source URL

To trace the caller function's details, including the line number and source URL, consider the following approach:

Getting the Caller Function Name:

<br>var callerFunc = arguments.callee.caller.toString();<br>callerFuncName = (callerFunc.substring(callerFunc.indexOf("function")   8, callerFunc.indexOf("(")) || "anoynmous")<br>

This code snippet obtains the name of the caller function.

Retrieving the Caller Line Number:

To get the line number from which the caller function was invoked:

function getErrorObject() {
    try {
        throw Error('');
    } catch (err) {
        return err;
    }
}

var err = getErrorObject();
var caller_line = err.stack.split("\n")[4];
var index = caller_line.indexOf("at ");
var clean = caller_line.slice(index + 2, caller_line.length);
Copy after login

This method leverages the JavaScript error object's stack property to access the caller's line number.

Determining the Caller Source URL:

Unfortunately, it is not straightforward to obtain the source URL directly from the caller function. However, you can use a bundler like webpack with source maps to generate a mapping between the bundled code and the source files, allowing you to map the caller's line number to its original source location.

The above is the detailed content of How to Trace Caller Function Details (Line Number and Source URL) in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!