Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace Head script using Greasemonkey code

i want to replace "script.js" to "demo.js". anyone please help me

<head>

    <script src="script.js" type="text/javascript" language="javaScript"></script>     

</head>
like image 492
Noor Alam Avatar asked Dec 15 '22 07:12

Noor Alam


1 Answers

Run your script early by @run-at document-start. Add an event listener beforescriptexecute and check the script source. When you detect the desired script, call preventDefault method of the event and replace the script tag in the DOM.

// ==UserScript==
// @name        demo-scriptreplace
// @include     http://example.com/*
// @version     1
// @run-at      document-start
// ==/UserScript==

window.addEventListener('beforescriptexecute',
  function(event)
  {
    var originalScript = event.target;

    // debug output of full qualified script url
    console.log('script detected:', originalScript.src);

    // script ends with 'originalscript.js' ?
    // you can test as well: '<full qualified url>' === originalScript.src
    if(/\/originalscript\.js$/.test(originalScript.src)) 
    { 
      var replacementScript = document.createElement('script');
      replacementScript.src = 'replacementscript.js';

      originalScript.parentNode.replaceChild(replacementScript, originalScript);

      // prevent execution of the original script
      event.preventDefault();
    }
  }
);
like image 190
Quasimodo's clone Avatar answered Jan 03 '23 10:01

Quasimodo's clone