Trouble debugging content scripts in a chrome exte

2019-04-11 01:43发布

问题:

To load modules in the content scripts I'm using the following code (source http://prezi.com/rodnyr5awftr/requirejs-in-chrome-extensions/):

require.load = function (context, moduleName, url) {
    var xhr;
    xhr = new XMLHttpRequest();
    xhr.open("GET", chrome.extension.getURL(url) + '?r=' + new Date().getTime(), true);
    xhr.onreadystatechange = function (e) {
        if (xhr.readyState === 4 && xhr.status === 200) {
            eval(xhr.responseText);
            context.completeLoad(moduleName)
        }
    };
    xhr.send(null);
};

The trouble happens when debugging via the Chrome console. Whenever there is an error in one of my modules it just reports the error occurred in an anonymous function but doesn't inform me which require.js module or line in that module the error occurred but instead always points back to the eval line in the above script.

Since a lot of people seem to being using different variations of the above code when using require.js with chrome extensions, there must be a simple way to get more information in the debugging console, I just don't what that is :).

Thanks for your help!!

UPDATE 4/1: Changing the eval() statement above to use Function() seems to have solved the problem in that the chrome console adds in the addition information. (credit for this work around goes to this question).

I realize the two functions aren't totally interchangeable (see this question). If anyone is aware of any pitfalls in using Function() instead of eval() in the above code please let me know!!

回答1:

You can change the line

        eval(xhr.responseText);

by

        eval(xhr.responseText + "\n//@ sourceURL=" + url);

This way you'll see all your evaled code listed in the source code panel under its original url.