Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting HTTP event using JQuery

I have this JQuery code working however I need to know whether how to actually get the URL executed from the tags selected.

$("link, script, style, a, img").each(function () {
    $(this).load(function () {
        // get the URL and log it
        console.log("Intercepted HTTP Event");
    });
});

First thing I need to do it to get the actual URL during the load.

Next thing I may need to do is to actually catch before the load event happens, I mean before an image or link is loaded for example. Also, I need to modify the URL of the event that will be executed, for example, img tag has src="/somewhere/image.png" I mean, this will cause a GET /somewhere/image.png I may need to change it to GET/otherplace/image.png

Any ideas how to achive any of these?


1 Answers

$(this).load() will fire after the contents of the element have been loaded. So you may be able to grab the URL by doing $(this).attr("src") or $(this).attr("href"), but it's already too late to stop the HTTP requests from going out.

AFAIK, with modern browsers, there's no way for JavaScript to prevent assets from being loaded in the first place. At best, you may be able to change images and stylesheets after the page has been loaded, by changing the src attributes. If you do this, make sure that $(this).load() doesn't go into an infinite loop. (<a> links are less of a problem. Nothing is loaded, so just change the href attribute.)

like image 107
kijin Avatar answered Nov 24 '25 05:11

kijin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!