停止执行 Javascript 函数(客户端)或对其进行调整

发布于 2024-09-28 08:26:02 字数 196 浏览 1 评论 0原文

我想停止执行站点中的一行,以便浏览器读取除该行之外的整个页面。或者浏览器可能会简单地跳过该 JavaScript 函数的执行。

或者

有没有办法我可以以某种方式调整javascript,以便javascript中的随机数生成函数不会生成随机数,但我想要的数字......

我无权访问托管脚本的网站,所以所有这些都需要在客户端完成。

I want to stop the execution of one single line from a site, so that the whole page is read by the browser except that single line. Or the browser may simply skip the execution of that javascript function.

OR

Is there way i can tweak the javascript somehow so that the random number generating function in javascript do not generate random number, but the numbers i want...

I dont have access to the site on which the script is hosted so all this needs to be done client side.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

绝不服输 2024-10-05 08:26:02

Firefox 目前支持beforescriptexecute 事件< /a>(自版本 4 起,于 2011 年 3 月 22 日发布‡< /sup>。

通过该事件和 // @run-at document-start 指令,Firefox 和 Greasemonkey 现在似乎在拦截特定

这对于 Chrome+Tampermonkey 来说仍然不可能。对于除 Firefox+Greasemonkey 之外的任何内容,您将需要使用下面其他答案中所示的技术来编写完整的浏览器扩展。

checkForBadJavascripts 函数对此进行了封装。例如,假设页面有一个

<script>
    alert ("Sorry, Sucka!  You've got no money left.");
</script>

您可以像这样使用 checkForBadJavascripts

checkForBadJavascripts ( [
    [   false, 
        /Sorry, Sucka/, 
        function () {
            addJS_Node ('alert ("Hooray, you\'re a millionaire.");');
        } 
    ]
] );

获得更好的消息。 (^_^)
有关更多信息,请参阅 checkForBadJavascripts 中的内联文档。


要查看完整脚本的演示,请首先访问 jsBin 页面。你会看到 3 行文本,其中两行是 JS 添加的。

现在,安装此脚本 (查看源代码;也在下面。)并重新访问该页面。您将看到 GM 脚本删除了一个坏标签,并用我们的“好”JS 替换了另一个标签。


请注意,只有 Firefox 支持 beforescriptexecute 事件。它已从 HTML5 规范中删除,且未指定等效功能。



完整的 GM 脚本示例(与 GitHub 和 jsBin 上的相同):

给定以下 HTML:

<body onload="init()">
<script type="text/javascript" src="http://jsbin.com/evilExternalJS/js"></script>
<script type="text/javascript" language="javascript">
    function init () {
        var newParagraph            = document.createElement ('p');
        newParagraph.textContent    = "I was added by the old, evil init() function!";
        document.body.appendChild (newParagraph);
    }
</script>
<p>I'm some initial text.</p>
</body>

使用这个 Greasemonkey 脚本:

// ==UserScript==
// @name        _Replace evil Javascript
// @include     http://jsbin.com/ogudon*
// @run-at      document-start
// ==/UserScript==

/****** New "init" function that we will use
    instead of the old, bad "init" function.
*/
function init () {
    var newParagraph            = document.createElement ('p');
    newParagraph.textContent    = "I was added by the new, good init() function!";
    document.body.appendChild (newParagraph);
}

/*--- Check for bad scripts to intercept and specify any actions to take.
*/
checkForBadJavascripts ( [
    [false, /old, evil init()/, function () {addJS_Node (init);} ],
    [true,  /evilExternalJS/i,  null ]
] );

function checkForBadJavascripts (controlArray) {
    /*--- Note that this is a self-initializing function.  The controlArray
        parameter is only active for the FIRST call.  After that, it is an
        event listener.

        The control array row is  defines like so:
        [bSearchSrcAttr, identifyingRegex, callbackFunction]
        Where:
            bSearchSrcAttr      True to search the SRC attribute of a script tag
                                false to search the TEXT content of a script tag.
            identifyingRegex    A valid regular expression that should be unique
                                to that particular script tag.
            callbackFunction    An optional function to execute when the script is
                                found.  Use null if not needed.
    */
    if ( ! controlArray.length) return null;

    checkForBadJavascripts      = function (zEvent) {

        for (var J = controlArray.length - 1;  J >= 0;  --J) {
            var bSearchSrcAttr      = controlArray[J][0];
            var identifyingRegex    = controlArray[J][1];

            if (bSearchSrcAttr) {
                if (identifyingRegex.test (zEvent.target.src) ) {
                    stopBadJavascript (J);
                    return false;
                }
            }
            else {
                if (identifyingRegex.test (zEvent.target.textContent) ) {
                    stopBadJavascript (J);
                    return false;
                }
            }
        }

        function stopBadJavascript (controlIndex) {
            zEvent.stopPropagation ();
            zEvent.preventDefault ();

            var callbackFunction    = controlArray[J][2];
            if (typeof callbackFunction == "function")
                callbackFunction ();

            //--- Remove the node just to clear clutter from Firebug inspection.
            zEvent.target.parentNode.removeChild (zEvent.target);

            //--- Script is intercepted, remove it from the list.
            controlArray.splice (J, 1);
            if ( ! controlArray.length) {
                //--- All done, remove the listener.
                window.removeEventListener (
                    'beforescriptexecute', checkForBadJavascripts, true
                );
            }
        }
    }

    /*--- Use the "beforescriptexecute" event to monitor scipts as they are loaded.
        See https://developer.mozilla.org/en/DOM/element.onbeforescriptexecute
        Note that it does not work on acripts that are dynamically created.
    */
    window.addEventListener ('beforescriptexecute', checkForBadJavascripts, true);

    return checkForBadJavascripts;
}

function addJS_Node (text, s_URL, funcToRun) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    //--- Don't error check here. if DOM not available, should throw error.
    targ.appendChild (scriptNode);
}

Firefox currently supports the beforescriptexecute event (as of Version 4, released on March 22, 2011).

With that event and the // @run-at document-start directive, Firefox and Greasemonkey now seem to do a good job intercepting specific <script> tags.

This is still not possible for Chrome+Tampermonkey. For anything but Firefox+Greasemonkey, you will need to use techniques as shown in the other answers, below, of write a full browser extension.

The checkForBadJavascripts function encapsulates this. For example, suppose the page had a <script> tag like so:

<script>
    alert ("Sorry, Sucka!  You've got no money left.");
</script>

You could use checkForBadJavascripts like so:

checkForBadJavascripts ( [
    [   false, 
        /Sorry, Sucka/, 
        function () {
            addJS_Node ('alert ("Hooray, you\'re a millionaire.");');
        } 
    ]
] );

to get a much nicer message. (^_^)
See the inline documentation, in checkForBadJavascripts, for more.


To see a demonstration in a complete script, first visit this page at jsBin. You will see 3 lines of text, two of them added by JS.

Now, install this script (View source; it's also below.) and revisit the page. You will see that the GM-script deleted one bad tag and replaced another with our "good" JS.


Note that only Firefox supports the beforescriptexecute event. And it was removed from the HTML5 spec with no equivalent capability specified.



Complete GM script example (The same as the one at GitHub and jsBin):

Given this HTML:

<body onload="init()">
<script type="text/javascript" src="http://jsbin.com/evilExternalJS/js"></script>
<script type="text/javascript" language="javascript">
    function init () {
        var newParagraph            = document.createElement ('p');
        newParagraph.textContent    = "I was added by the old, evil init() function!";
        document.body.appendChild (newParagraph);
    }
</script>
<p>I'm some initial text.</p>
</body>

Use this Greasemonkey script:

// ==UserScript==
// @name        _Replace evil Javascript
// @include     http://jsbin.com/ogudon*
// @run-at      document-start
// ==/UserScript==

/****** New "init" function that we will use
    instead of the old, bad "init" function.
*/
function init () {
    var newParagraph            = document.createElement ('p');
    newParagraph.textContent    = "I was added by the new, good init() function!";
    document.body.appendChild (newParagraph);
}

/*--- Check for bad scripts to intercept and specify any actions to take.
*/
checkForBadJavascripts ( [
    [false, /old, evil init()/, function () {addJS_Node (init);} ],
    [true,  /evilExternalJS/i,  null ]
] );

function checkForBadJavascripts (controlArray) {
    /*--- Note that this is a self-initializing function.  The controlArray
        parameter is only active for the FIRST call.  After that, it is an
        event listener.

        The control array row is  defines like so:
        [bSearchSrcAttr, identifyingRegex, callbackFunction]
        Where:
            bSearchSrcAttr      True to search the SRC attribute of a script tag
                                false to search the TEXT content of a script tag.
            identifyingRegex    A valid regular expression that should be unique
                                to that particular script tag.
            callbackFunction    An optional function to execute when the script is
                                found.  Use null if not needed.
    */
    if ( ! controlArray.length) return null;

    checkForBadJavascripts      = function (zEvent) {

        for (var J = controlArray.length - 1;  J >= 0;  --J) {
            var bSearchSrcAttr      = controlArray[J][0];
            var identifyingRegex    = controlArray[J][1];

            if (bSearchSrcAttr) {
                if (identifyingRegex.test (zEvent.target.src) ) {
                    stopBadJavascript (J);
                    return false;
                }
            }
            else {
                if (identifyingRegex.test (zEvent.target.textContent) ) {
                    stopBadJavascript (J);
                    return false;
                }
            }
        }

        function stopBadJavascript (controlIndex) {
            zEvent.stopPropagation ();
            zEvent.preventDefault ();

            var callbackFunction    = controlArray[J][2];
            if (typeof callbackFunction == "function")
                callbackFunction ();

            //--- Remove the node just to clear clutter from Firebug inspection.
            zEvent.target.parentNode.removeChild (zEvent.target);

            //--- Script is intercepted, remove it from the list.
            controlArray.splice (J, 1);
            if ( ! controlArray.length) {
                //--- All done, remove the listener.
                window.removeEventListener (
                    'beforescriptexecute', checkForBadJavascripts, true
                );
            }
        }
    }

    /*--- Use the "beforescriptexecute" event to monitor scipts as they are loaded.
        See https://developer.mozilla.org/en/DOM/element.onbeforescriptexecute
        Note that it does not work on acripts that are dynamically created.
    */
    window.addEventListener ('beforescriptexecute', checkForBadJavascripts, true);

    return checkForBadJavascripts;
}

function addJS_Node (text, s_URL, funcToRun) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
    //--- Don't error check here. if DOM not available, should throw error.
    targ.appendChild (scriptNode);
}
走走停停 2024-10-05 08:26:02

方法 1:使用 MutationObserver

beforescriptexecute 在 Firefox 中不再有效,在 Chrome 中也不起作用。幸运的是,还有一个替代方案,使用 MutationObserver,得到了相当广泛的支持。总体思路是在页面加载开始时添加一个 MutationObserver,每当新节点添加到 DOM 时,它将运行回调。在回调中,检查是否存在要更改或删除的

<script>
  // This is the userscript code, which runs at the beginning of pageload
  // Say we wanted to prevent the loading of the jQuery script tag below:
  new MutationObserver((_, observer) => {
    const jqueryScriptTag = document.querySelector('script[src*="jquery"]');
    if (jqueryScriptTag) {
      console.log('Found jQuery script tag; now removing it!');
      jqueryScriptTag.remove();
      // We've done what we needed to do, no need for the MutationObserver anymore:
      observer.disconnect();
    }
  })
    .observe(document.documentElement, { childList: true, subtree: true });
</script>
<div>Example content</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
  console.log('After jQuery script tag. If done right, $ should be undefined:');
  console.log(typeof $);
</script>

下面是一个示例用户脚本,它阻止 jQuery 在 Stack Overflow 上的 中加载:

// ==UserScript==
// @name             Example jQuery removal
// @include          https://stackoverflow.com*
// @run-at           document-start
// @grant            none
// ==/UserScript==

if (document.head) {
  throw new Error('Head already exists - make sure to enable instant script injection');
}
new MutationObserver((_, observer) => {
  const jqueryScriptTag = document.querySelector('script[src*="jquery"]');
  if (jqueryScriptTag) {
    jqueryScriptTag.remove();
    observer.disconnect();
  }
})
  .observe(document.documentElement, { childList: true, subtree: true });

如果安装此脚本,您将看到 jQuery 加载失败,从而导致生成大量错误Stack Overflow 的 JS。

确保尽快附加 MutationObserver - 您需要 @run-at document-start 在页面加载 内的任何内容之前附加它。 (如果使用 Tampermonkey / Chrome,您可能需要启用实验性即时脚本注入才能可靠地实现此目的 - 转到 Tampermonkey 设置,配置模式:高级,滚动到底部,将实验注入模式设置为即时。)

如果您正在编写用户脚本对于其他人,如果您使用此技术,请确保包含即时脚本注入的说明,因为默认情况下,Chrome 上的注入不是即时的。

请注意,观察者是使用附加的。

.observe(document.documentElement, { childList: true, subtree: true });

这将观察者附加到 元素,使用 childList: true 监视添加和删除的直接子级,并监视添加和删除的直接子级。使用 subtree: true 删除了其后代中任何位置的节点。这样的递归侦听器很有用,但在大型动态页面上它的计算成本也很高,因此请确保在它达到其目的后将其删除。

在一个巨大的页面上,对每个突变调用 querySelector 的成本可能很高,因此您可能需要迭代 mutations (观察者回调的第一个参数)和突变' addedNodes 相反:

<script>
  // This is the userscript code, which runs at the beginning of pageload
  // Say we wanted to prevent the loading of the jQuery script tag below:
  new MutationObserver((mutations, observer) => {
    for (const mutation of mutations) {
      for (const addedNode of mutation.addedNodes) {
        if (addedNode.nodeType === 1 && addedNode.matches('script[src*="jquery"]')) {
          console.log('Found jQuery script tag; now removing it!');
          addedNode.remove();
          // We've done what we needed to do, no need for the MutationObserver anymore:
          observer.disconnect();
          return;
        }
      }
    }
  })
    .observe(document.documentElement, { childList: true, subtree: true });
</script>
<div>Example content</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
  console.log('After jQuery script tag. If done right, $ should be undefined:');
  console.log(typeof $);
</script>

您还可以通过在观察者回调中分配给内联脚本的 textContent 来调整内联脚本。以下代码片段展示了如何更改随机数生成器函数以始终返回 10,而不是 1-6:

<script>
  // This is the userscript code, which runs at the beginning of pageload
  new MutationObserver((mutations, observer) => {
    for (const mutation of mutations) {
      for (const addedNode of mutation.addedNodes) {
        if (addedNode.textContent.includes('const randomNum')) {
          addedNode.textContent = addedNode.textContent.replace(
            /const randomNum.*/,
            'const randomNum = 10;'
          );
          observer.disconnect();
          return;
        }
      }
    }
  })
    .observe(document.documentElement, { childList: true, subtree: true });
</script>
<button>Roll Die</button>
<div>Results: <span></span></div>
<script>
const [button, span] = ['button', 'span'].map(tag => document.querySelector(tag));
button.onclick = () => {
  const randomNum = Math.ceil(Math.random() * 6);
  span.textContent = randomNum;
};
</script>


方法 2:使用 DevTools 本地覆盖

方法 1 是为其他编写用户脚本时可以使用的技术。但是,如果用户脚本仅用于您自己,则有一种更简单的方法可以在某些情况下使用。请参阅问题 Chrome 开发工具 - 修改 JavaScript 并重新加载的答案:转到来源 -> Chrome Devtools 中的“覆盖”选项卡,并启用本地覆盖,您可以告诉浏览器加载 .js 的本地副本,而不是下载网站的版本。然后,您可以根据需要编辑本地副本,它将代替内置脚本运行。这在调整大型 Javascript 文件时特别有用 - 它比 MutationObserver 方法更易于管理。

但是,也有一些缺点:

  • 要修改内联 标记,您必须下载页面的本地副本。 (因此,如果页面通过 HTML 响应提供动态内容,您要么必须重新保存并重新调整 .html 以便覆盖才能使用新内容,要么您将回到 MutationObserver 方法。)
  • 这是一种开发人员可能能够理解的技术(经过一些实验),但它不是那么用户友好。这可能不是您想要引导临时用户脚本消费者完成的事情。

Method 1: using MutationObserver

beforescriptexecute no longer works in Firefox, nor did it work in Chrome. Luckily, there's an alternative, using MutationObserver, which is quite widely supported. The general idea is to add a MutationObserver at the beginning of pageload, which will run a callback whenever a new node is added to the DOM. Inside the callback, check for the existence of the <script> tag you want to alter or remove. If it exists, you can tamper with it (such as change its textContent, or have its src point somewhere else). Only after the callback finishes will the newly added script tag run, so this is an effective way to intercept and change Javascript on a page. Here's a live snippet example:

<script>
  // This is the userscript code, which runs at the beginning of pageload
  // Say we wanted to prevent the loading of the jQuery script tag below:
  new MutationObserver((_, observer) => {
    const jqueryScriptTag = document.querySelector('script[src*="jquery"]');
    if (jqueryScriptTag) {
      console.log('Found jQuery script tag; now removing it!');
      jqueryScriptTag.remove();
      // We've done what we needed to do, no need for the MutationObserver anymore:
      observer.disconnect();
    }
  })
    .observe(document.documentElement, { childList: true, subtree: true });
</script>
<div>Example content</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
  console.log('After jQuery script tag. If done right, $ should be undefined:');
  console.log(typeof $);
</script>

Here's an example userscript that blocks jQuery from loading in the <head> here on Stack Overflow:

// ==UserScript==
// @name             Example jQuery removal
// @include          https://stackoverflow.com*
// @run-at           document-start
// @grant            none
// ==/UserScript==

if (document.head) {
  throw new Error('Head already exists - make sure to enable instant script injection');
}
new MutationObserver((_, observer) => {
  const jqueryScriptTag = document.querySelector('script[src*="jquery"]');
  if (jqueryScriptTag) {
    jqueryScriptTag.remove();
    observer.disconnect();
  }
})
  .observe(document.documentElement, { childList: true, subtree: true });

If you install this, you'll see that the loading of jQuery fails, resulting in lots of errors generated by Stack Overflow's JS.

Make sure to attach the MutationObserver as soon as possible - you need @run-at document-start to attach it before the page loads anything inside the <head>. (If using Tampermonkey / Chrome, you may need to enable experimental instant script injection to achieve this reliably - go to Tampermonkey Settings, Config mode: Advanced, scroll to the bottom, set Experimental Inject Mode to Instant.)

If you're writing userscripts for others, any you're using this technique, make sure to include instructions for instant script injection, since injection is not instant by default on Chrome.

Note that the observer is attached using

.observe(document.documentElement, { childList: true, subtree: true });

This attaches the observer to the <html> element, watches for added and removed immediate children with childList: true, and watches for added and removed nodes anywhere inside its descendants with subtree: true. Such a recursive listener is useful, but it's also computationally expensive on large dynamic pages, so make sure to remove it once it's achieved its purpose.

On a huge page, calling querySelector on every mutation could be costly, so you might want to iterate through the mutations (the first parameter to the observer's callback) and the mutations' addedNodes instead:

<script>
  // This is the userscript code, which runs at the beginning of pageload
  // Say we wanted to prevent the loading of the jQuery script tag below:
  new MutationObserver((mutations, observer) => {
    for (const mutation of mutations) {
      for (const addedNode of mutation.addedNodes) {
        if (addedNode.nodeType === 1 && addedNode.matches('script[src*="jquery"]')) {
          console.log('Found jQuery script tag; now removing it!');
          addedNode.remove();
          // We've done what we needed to do, no need for the MutationObserver anymore:
          observer.disconnect();
          return;
        }
      }
    }
  })
    .observe(document.documentElement, { childList: true, subtree: true });
</script>
<div>Example content</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
  console.log('After jQuery script tag. If done right, $ should be undefined:');
  console.log(typeof $);
</script>

You can also tweak inline scripts by assigning to their textContent inside the observer callback. The following snippet shows how you can change a random number generator function to always return 10, rather than 1-6:

<script>
  // This is the userscript code, which runs at the beginning of pageload
  new MutationObserver((mutations, observer) => {
    for (const mutation of mutations) {
      for (const addedNode of mutation.addedNodes) {
        if (addedNode.textContent.includes('const randomNum')) {
          addedNode.textContent = addedNode.textContent.replace(
            /const randomNum.*/,
            'const randomNum = 10;'
          );
          observer.disconnect();
          return;
        }
      }
    }
  })
    .observe(document.documentElement, { childList: true, subtree: true });
</script>
<button>Roll Die</button>
<div>Results: <span></span></div>
<script>
const [button, span] = ['button', 'span'].map(tag => document.querySelector(tag));
button.onclick = () => {
  const randomNum = Math.ceil(Math.random() * 6);
  span.textContent = randomNum;
};
</script>


Method 2: using DevTools Local Overrides

Method 1 is the technique you can use when writing userscripts for others. But if the userscript is just for yourself, there's an easier method that can work in some situations. See this answer to the question Chrome Dev Tools - Modify javascript and reload: by going to the Sources -> Overrides tab in Chrome Devtools, and enabling local overrides, you can tell the browser to load a local copy of a .js instead of downloading the site's version. Then you can edit the local copy as desired, and it'll run instead of the built-in script. This is especially useful when tweaking large Javascript files - it's much more manageable than the MutationObserver approach.

But, there are some downsides:

  • To modify inline <script>// code here</script> tags, you'll have to download a local copy of the page. (So if the page serves dynamic content through the HTML response, you'll either have to re-save and re-tweak the .html for your overrides to use the new content, or you'll have to go back to the MutationObserver method.)
  • This is a technique developers may be able to understand (after some experimenting), but it's not so user-friendly. It may not be the sort of thing you'd want to walk a casual userscript consumer through.
怼怹恏 2024-10-05 08:26:02

答案取决于未提供的详细信息(最好是确切的页面和代码行),但一般情况下是这样的:

  1. 如果有问题的 JS 代码没有立即触发 (在 DOMContentLoaded 之后触发),然后您可以使用 Greasemonkey 替换有问题的代码。  例如:

    var scriptNode = document.createElement("脚本");
    scriptNode.textContent = "这里是你的 JS 代码";
    document.head.appendChild(scriptNode);
    

    完成。

  2. 如果JS代码立即触发,那么事情就会变得更加复杂。
    首先,获取脚本的副本并对其进行所需的更改。将其保存在本地。

  3. 有问题的脚本是在文件中还是在主页 HTML 中(

  4. 如果脚本位于文件中,请安装 Adblock Plus 并使用它来阻止加载该脚本。然后使用 Greasemonkey 将修改后的代码添加到页面中。例如:

    var scriptNode = document.createElement("脚本");
    scriptNode.setAttribute("src", "这里指向你修改的JS文件。");
    document.head.appendChild(scriptNode);
    
  5. 如果脚本位于 HTML 主页面中,则安装 NoScript (最好)或 YesScript 并使用它来阻止来自该网站的 JavaScript。
    这意味着您需要使用 Greasemonkey 替换该站点中您确实想要运行的所有脚本。

The answer depends on details which were not provided (The exact page and line of code would be best), but here's how you do it in general:

  1. If the offending JS code does not fire right away (Fires after DOMContentLoaded), then you can use Greasemonkey to replace the offending code.   EG:

    var scriptNode          = document.createElement ("script");
    scriptNode.textContent  = "Your JS code here";
    document.head.appendChild (scriptNode);
    

    Done.

  2. If the JS code fires immediately, then it gets more complicated.
    First, grab a copy of the script and make the desired change to it. Save this locally.

  3. Is the offending script in a file or is it in the main page HTML (<script src="Some File> versus <script>Mess O' Code</script>)?

  4. If the script is in a file, install Adblock Plus and use it to block loading of that script. Then use Greasemonkey to add your modified code to the page. EG:

    var scriptNode          = document.createElement ("script");
    scriptNode.setAttribute ("src", "Point to your modified JS file here.");
    document.head.appendChild (scriptNode);
    
  5. If the script is in the main HTML page, then install either NoScript (best) or YesScript and use it to block JavaScript from that site.
    This means that you will then need to use Greasemonkey to replace all scripts, from that site, that you do want to run.

柳若烟 2024-10-05 08:26:02

您可以使用所谓的小书签。

构建要在其他站点上运行的 js 文件: your.js

使用以下代码创建 HTML 页面:

<html>
<body>
  <a href="javascript:(function(){var s=document.createElement('SCRIPT');s.src='/url/to/your.js?'+(Math.random());document.getElementsByTagName('head')[0].appendChild(s);})()">
    Drag'n Drop this to your bookmarks
  </a>
</body>
</html>

/url/to/your.js 替换为你的js文件的路径。

在浏览器中加载该小页面,然后将链接拖放到书签栏。

转到您想要破解的网站,然后单击您刚刚创建的书签。
这将在页面中加载 your.js 并运行代码。

注意?'+(Math.random())部分是为了避免你的js被缓存,这不是强制性的,但在你开发时很有帮助你的.js

You can use what is called a bookmarklet.

Build the js file you want to run on the other site: your.js

Make an HTML page with the following code:

<html>
<body>
  <a href="javascript:(function(){var s=document.createElement('SCRIPT');s.src='/url/to/your.js?'+(Math.random());document.getElementsByTagName('head')[0].appendChild(s);})()">
    Drag'n Drop this to your bookmarks
  </a>
</body>
</html>

Replace /url/to/your.js with the path of your js file.

Load that small page in your browser and drag'n drop the link to your bookmark bar.

Go to the web site you want to hack, and click the bookmark you just created.
This will load your.js in the page and run the code.

Note: the ?'+(Math.random()) part is to avoid your js being cached, this is not mandatory but it is helpful when you develop your.js

空城缀染半城烟沙 2024-10-05 08:26:02

使用 TamperMonkey?您需要在 TamperMonkey 标头中的 // @grant 下方添加 // @require http://urlofyoursite.com/myfile.js。例如,这是我的 TamperMonkey 东西的最顶部:

// ==UserScript==
// @name         Project
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://docs.google.com/presentation/*
// @grant        none
// @require http://cdnjs.cloudflare.com/ajax/libs/annyang/2.1.0/annyang.min.js
// ==/UserScript==

Using TamperMonkey? All you need to add below your // @grant in the TamperMonkey header is // @require http://urlofyoursite.com/myfile.js. For example, here is the very top of my TamperMonkey thingie:

// ==UserScript==
// @name         Project
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://docs.google.com/presentation/*
// @grant        none
// @require http://cdnjs.cloudflare.com/ajax/libs/annyang/2.1.0/annyang.min.js
// ==/UserScript==
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文