3

I tried unsuccessfully to make a script that deletes another script on a page.

The page loads 2 scripts in <body> that I don't want to execute:

<div id="myindex">
  <div class="wrap">
    <div id="idone"></div>
    <div id="idtwo"></div>
    <script type="text/javascript"></script>
    <script type="text/javascript"></script>
    <script type="text/javascript"></script> //To Remove
    <script type="text/javascript"></script> //To Remove
  </div>
</div>

How do I block just those scripts from running?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Kevin
  • 41
  • 1
  • 2

1 Answers1

1

This works splendidly with the new Greasemonkey @run-at directive!

Here is an example userscript: http://userscripts.org/scripts/show/125936

Important quote:

This user script will run right at the document beginning, as for Scriptish, it even runs before getting any HTTP response ( which is excellent for redirecting ).

It shows how to remove malicious JS from a website. Here is the full script example:

// ==UserScript==
// @name           editscript
// @version        0.0.1
// @namespace      example@example.com
// @include        http://*
// @run-at         document-start
// ==/UserScript==

var changed = 0; // script need to be edited with

window.addEventListener('beforescriptexecute', function(e) {

    ///for external script:
    src = e.target.src;
    if (src.search(/bad\.js/) != -1) {
                changed++;
        e.preventDefault();
        e.stopPropagation();
        append(NewScript1);
    };

    ///for inline script:
        if(e.target===document.getElementsByTagName("script")[0]){
            changed++;
            e.stopPropagation();
            e.preventDefault();
            //todo
        }
        //tips: you could also run a regex search for the e.target.innerHTML
        //if the position of the inline script is not fixed.


    ///when done, remove the listener:
    if(changed == 2) window.removeEventListener(e.type, arguments.callee, true);

}, true);



////// append with new block function:
function append(s) {     
      document.head.appendChild(document.createElement('script'))
             .innerHTML = s.toString().replace(/^function.*{|}$/g, '');
}

////////////////////////////////////////////////
function NewScript1(){
    /* insert new block here, like:  */
    function load_good_stuff(){
            /* we still got it!! 
             * only without the evil thing. 
             */
    }
};
Sarien
  • 6,647
  • 6
  • 35
  • 55
  • +1. Does work now for FF and Greasemonkey -- where it becomes a good solution. Does not work on Chrome and probably not Opera. – Brock Adams May 06 '12 at 05:19
  • great link, shows nothing -> always put the important information in your answer – sjngm Nov 20 '20 at 14:44