Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajaxComplete in pure JavaScript

I am building a chrome extension using Content Script.

I have a piece of code that injects DOM elements upon success of all ajax request on the page using jQuery. How can you recreate this without jQuery? Please note that I cannot modify any ajax requests on the page.

if(window.jQuery){
jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
    for(var i =0; i< $jq('div.handwave').length; i++){
        if($($('div.handwave')[i]).children('.done').length < 1){
            $(document).find('div.handwave').eq(i).append(wind);
        }
    }
});
}

Is this possible?

like image 260
xoail Avatar asked Jul 27 '17 02:07

xoail


1 Answers

Update

If you're writing a Chrome extension, you should probably use the chrome.webRequest API. See https://developer.chrome.com/extensions/webRequest


You can override one of the existing methods required to make an AJAX request such as XMLHttpRequest.prototype.send to add your own load event listener. For example

(function() {
    const send = XMLHttpRequest.prototype.send
    XMLHttpRequest.prototype.send = function() { 
        this.addEventListener('load', function() {
            console.log('global handler', this.responseText)
            // add your global handler here
        })
        return send.apply(this, arguments)
    }
})()

As mentioned in the comments, this won't cover the fetch API.

like image 126
Phil Avatar answered Oct 12 '22 06:10

Phil