Javascript - get a node link to a script tag that calls a function

How can I get a link to the DOM script tag that called the function?

For instance:

<script type="text/javascript">
    var globalfunc = function(){
        //obtain a reference to the script block that globalfunc() was called from
    }
</script>

<script type="text/javascript">
    globalfunc();
</script>

I know that I could assign an id or class to a script element and pass it to my function to perform a DOM search, but I think it would be more flexible and elegant to do this without such a thing. The main reason is that I may have to do some work on our site so that third-party ads break into the form and we don’t have control over the scripts that they use to load their ads.

+3
source share
3 answers

id script, . , , .

, , - :

var scripts = document.getElementsByTagName("script");

for (var i=0, l=scripts.length; i<l; ++i ) {
  if ( scripts[i].innerHTML.indexOf("globalfunc();") != -1 ) {
     // Found a script tag in which `globalfunc();` is executed
  }
}
+1

, script , , script . -

var scripts = document.getElementsByTagName("script");
var scriptElement = scripts[scripts.length-1];

.

, , :

var old_global = globalFunction;
globalFunction = function () {
    var scripts = document.getElementsByTagName("script");
    var scriptElement = scripts[scripts.length-1];

    old_global.call(this,arguments);

    // do something after
};

, .

+2

: , IE, , ( Firefox, ), script (<script src="...">), .

var getErrorScriptNode = (function () {
    var getErrorSource = function (error) {
        var loc, replacer = function (stack, matchedLoc) {
            loc = matchedLoc;
        };

        if ("fileName" in error) {
            loc = error.fileName;
        } else if ("stacktrace" in error) { // Opera
            error.stacktrace.replace(/Line \d+ of .+ script (.*)/gm, replacer);
        } else if ("stack" in error) { // WebKit
            error.stack.replace(/at (.*)/gm, replacer);
            loc = loc.replace(/:\d+:\d+$/, "");
        }
        return loc;
    },
    anchor = document.createElement("a");

    return function (error) {
        anchor.href = getErrorSource(error);
        var src = anchor.href,
        scripts = document.getElementsByTagName("script");
        anchor.removeAttribute("href");
        for (var i = 0, l = scripts.length; i < l; i++) {
            anchor.href = scripts.item(i).src;
            if (anchor.href === src) {
                anchor.removeAttribute("href");
                return scripts.item(i);
            }
        }
    };
}());

var globalfunc = function (err) {
    var scriptNode = getErrorScriptNode(err);
    // ...
};

In an external (must be EXTERNAL) script that calls globalfunc():

try {
    0();
} catch (e) {
    var err = e;
}
// do stuff...
globalfunc(err);
+1
source

Source: https://habr.com/ru/post/1725897/


All Articles