how to replace Head script using Greasemonkey code

回眸只為那壹抹淺笑 提交于 2019-12-12 13:41:33

问题


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>

回答1:


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();
    }
  }
);



回答2:


The question is actually not really descriptive, but Greasemonkey is actually using javascript. So let's assume you have "head" element in your page and you want this as a single element inside of "head" element.

That in Javascript you can achieve this by following:

var e = '<script src="script.js" type="text/javascript" language="javaScript"></script>';
document.head.innerHTML = e;

In order to append it you can just add plus sign infront of equal sign in second command:

var e = '<script src="script.js" type="text/javascript" language="javaScript"></script>';
document.head.innerHTML += e;

EDIT: Eventually, if you have single script element pointing to such source javascript file, you can also use this to identify element and replace attribute value directly:

document.querySelectorAll('script[src="script.js"]')[0].setAttribute('src','demo.js');

EDIT: Important to point out is, that this answers the question how to replace. You still may need to prevent original script from being executed as mentioned by Quasimodo (though it was not part of question)



来源:https://stackoverflow.com/questions/36605989/how-to-replace-head-script-using-greasemonkey-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!