Greasemonkey - replace javascript src to load custom JS instead the one of the page

折月煮酒 提交于 2019-12-05 02:02:35

问题


There's specific webpage with variable in .js file. I want to rewrite the URL to be loaded with Greasemonkey, but still haven't got any results.The code I use is:

window.addEventListener(
    'load', 
    function() { 
        allTextareas = document.getElementsByTagName('script');
        for (thisTextarea in allTextareas) {
            if( allTextareas[thisTextarea].getAttribute('src') == 'some url.js' ){
                 //allTextareas[thisTextarea].setAttribute('src', 'http://my custom url.js');   


            }
        }

     },
    true);

but it's not working. Can you help me, or just tell me a way to edit JS files on specific page..


回答1:


A couple things, easy one first...

(1) In GM, you cannot iterate collections that way. So instead of:

for (thisTextarea in allTextareas) {
    if (allTextareas[thisTextarea].getAttribute('src') == 'some url.js') {


You must use:

for (var J = allTextareas.length - 1;  J>=0;  --J) {
    if (allTextareas[J].getAttribute('src') == 'some url.js') {
    etc.


(2) By the time Greasemonkey fires, those scripts will have already loaded. Rewriting the script tag source may not do anything except cause flaky operation.

Block those scripts from loading at all, then use GM to rewrite their src -- or better yet, just create new <script> tags with the JS you want.

To block those scripts you will need a new add-on. Here are four that can do the job... best, but most-intrusive, first:

  1. RequestPolicy
  2. Adblock Plus
  3. NoScript
  4. YesScript

All of these add-ons have the benefits of reducing your vulnerability to bad scripts/sites/flash, and of speeding up page loads.



来源:https://stackoverflow.com/questions/5072702/greasemonkey-replace-javascript-src-to-load-custom-js-instead-the-one-of-the-p

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