How do I use JavaScript to store “XHR finished loading” messages in the console in Chrome?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-17 06:54:24

问题


I'm looking for a way to use JavaScript to store debug messages that appear in the Chrome console when xmlhttprequests are performed. Example output provided below:

Thanks in advance!


回答1:


You cannot read console messages from JavaScript. You will not be able to read these messages.

However, using the same general concept as John Culviner's answer to Add a “hook” to all AJAX requests on a page, you can detect the events in JavaScript that cause these messages to appear.

(function() {
    var origOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(method, url) {
        this.addEventListener('load', function() {
            console.log('XHR finished loading', method, url);
        });

        this.addEventListener('error', function() {
            console.log('XHR errored out', method, url);
        });
        origOpen.apply(this, arguments);
    };
})();

This overwrites every XHR object's open method with a new function that adds load and error listeners to the XHR request. When the request completes or errors out, the functions have access to the method and url variables that were used with the open method.

You can do something more useful with method and url than simply passing them into console.log if you wish.




回答2:


possible dublicate How to read from Chrome's console in JavaScript



来源:https://stackoverflow.com/questions/43282885/how-do-i-use-javascript-to-store-xhr-finished-loading-messages-in-the-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!