ajaxComplete in pure JavaScript

10,209

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.

Share:
10,209
xoail
Author by

xoail

Love building software solutions. Various technologies and domains. BY DAY: Software engineer at a nice ad agency. BY NIGHT: Solving my life problems through software FOR FUN: Hiking, running and netflix and chill. "Quotes are just quotes."-Me

Updated on June 14, 2022

Comments

  • xoail
    xoail over 1 year

    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?