防止执行特定的内联脚本标记 [英] Prevent execution of a specific inline script tag

查看:107
本文介绍了防止执行特定的内联脚本标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 Tampermonkey 编写一个脚本,以防止执行特定的内联脚本标记。页面正文看起来像这样

I'm trying to write a script for Tampermonkey that prevents the execution of a specific inline script tag. The body of the page looks something like this

<body>
  <!-- the following script tag should be executed-->
  <script type="text/javascript">
    alert("I'm executed as normal")
  </script>
  <!-- the following script tag should NOT be executed-->
  <script type="text/javascript">
    alert("I should not be executed")
  </script>
  <!-- the following script tag should be executed-->
  <script type="text/javascript">
    alert("I'm executed as normal, too")
  </script>
</body>

我试图删除脚本标签我的Tampermonkey脚本,但如果我 运行它document-start document-body 脚本标记尚不存在。如果我在 document-end document-idle 脚本标签在我的Tampermonkey脚本执行之前运行。

I tried to remove the script tag using my Tampermonkey script, but if I run it at document-start or document-body the script tag does not exist yet. If I run it at document-end or document-idle the script tag I'd like to remove is run before my Tampermonkey script is executed.

如何防止执行脚本标签?

注意:实际的脚本我想阻止执行的标记包含 window.location ='redirect-url'。因此,在这种情况下阻止重新加载也足够了。

Note: The actual script tag that I'd like to prevent from executing contains window.location = 'redirect-url'. So it would also be sufficient to prevent the reload in this case.

版本:


  • Chromium 65.0.3325.181

  • Tampermonkey 4.5

推荐答案

删除 document-start 上的脚本标记(由 wOxxOm ):

Delete script tag on document-start (as suggested by wOxxOm):

(function() {
    'use strict';
    window.stop();
    const xhr = new XMLHttpRequest();
    xhr.open('GET', window.location.href);
    xhr.onload = () => {
        var html = xhr.responseText
        .replace(/<script\b[\s\S]*?<\/script>/g, s => {
            // check if script tag should be replaced/deleted
            if (s.includes('window.location')) {
                return '';
            } else {
                return s;
            }
        });
        document.open();
        document.write(html);
        document.close();
    };
    xhr.send();
})();

这篇关于防止执行特定的内联脚本标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆