Getting control of every 'src' attribute change in DOM

277 Views Asked by At

I'm writing a Javascript code that needs to watch for new 'script' elements, and to block a few known sources.

To catch those, I've tried using MutationObserver and __ defineSetter __ , both can watch for the 'src' change, but only after the HTTP request is already being sent - so even if I change the src, it's not really being blocked.

window.HTMLScriptElement.prototype.__defineSetter__('src', function (d) 
    {
        console.log("HTMLScriptElement: ",d);
        if (d.indexOf('localhost') != -1) {
            //BLOCK SCRIPT
        }
    });

    new MutationObserver(function (a) {
        a.forEach((e) => {
            e.addedNodes.forEach((z) => 
            {
                if (z.nodeName.toLowerCase() == "script" && z.src.indexOf('localhost') != -1) 
                {
                    //BLOCK SCRIPT
                }
            })
        })
    }).observe(window.document, {
        attributes: true,
        childList:true,
        subtree:true
    });
1

There are 1 best solutions below

6
On

You could use Service workers in order to intercept network requests. Something like this should do the trick:

self.addEventListener('fetch', function (event) {
    const blockedUrls = [
        //...
    ];
    if (blockedUrls.some(x => event.request.url.startsWith(x))) {
        event.respondWith(new Response('blocked', { status: 401, statusText: 'Unauthorized' }));
    }
});