Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Greasemonkey script to turn off annoying things

Is there a way I can use Greasemonkey to selectively remove scripts on a site?

Disclaimer: I know JS but don't have much (read: none) direct experience with GM.

I just need to stop external scripts from loading (can't use NoScript because I want to load other less annoying scripts).

I tried doing this:

// ==UserScript==
// @name           turn_shit_off
// @namespace      http://www.google.com
// @include        http://www.xyz.com/*
// ==/UserScript==

window.onload = function() {
    var d = document;   // shorthand
    var scripts = d.getElementsByTagName('script');
    for(var i = 0; i < scripts.count; i++) {
        if(scripts[i].src.indexOf('foobar.js') != -1) {
            scripts[i].src = '';
        }
    }
}

But it doesn't work for me.

like image 580
capn Avatar asked Nov 05 '22 05:11

capn


1 Answers

Yes, Adblock Plus is the best way to go, if applicable.

The GM code may not fire in time to stop all the damage, but -- for giggles -- a working version of your code would be something like so:

// ==UserScript==
// @name           turn_shit_off
// @namespace      http://www.google.com
// @include        http://www.xyz.com/*
// ==/UserScript==

var scripts = document.getElementsByTagName('script');

for (var J = scripts.length-1;  J >=0;  --J)
{
    if (/foobar\.js/i.test (scripts[J].src) )
    {
        console.log ("Killed", scripts[J].src);
        scripts[J].parentNode.removeChild (scripts[J]);        
    }
}

/*--- Now you have to unload any unwanted event handlers and/or timers 
    that were set before the above code could fire.
    This is highly page-specific and may not be possible if anonymous
    functions were used.
*/


You will see that it actually removes the script elements.
But, alas, altering or removing the script elements, by itself, will have no effect most of the time.   Except, maybe, in delayed-load/run code (things that fire onload or that have the defer or async attributes set).

You won't have any effect until explicitly countering the handlers and timers that the bogus JS sets -- which is highly page-specific and not always possible.

Run this code to see for yourself.

like image 156
Brock Adams Avatar answered Nov 15 '22 07:11

Brock Adams