Get the url of currently executing js file when dynamically loaded

后端 未结 3 1770
萌比男神i
萌比男神i 2020-12-16 03:26

So I\'m trying to load a script dynamically and figure out the URL path at which that script was loaded. So some guy gave me a pretty awesome solution to this problem if the

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 03:41

    This will work in every browser except IE and doesn't depend on assuming what the name of a file is:

    var getErrorLocation = 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+$/, ""); // remove line number
        }
        return loc;
    };
    
    try {
        0();
    } catch (e) {
        var scriptURI = getErrorLocation(e);
    }
    
    alert("THIS IS: " + scriptURI);
    

提交回复
热议问题