xoail xoail - 2 years ago 134
Javascript Question

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.

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){

Is this possible?

Answer Source


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download