阻止执行特定的内联脚本标签

Prevent execution of a specific inline script tag

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

<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 脚本删除 script 标签,但是如果我 run it at document-startdocument-body script 标签不存在然而。如果我 运行 它位于 document-enddocument-idle 我想删除的 script 标签是 运行 在我的 Tampermonkey 脚本执行之前。

如何防止执行 script 标记?


注意: 我想阻止执行的实际 script 标记包含 window.location = 'redirect-url'。所以在这种情况下也足以防止重新加载。


版本:

删除 document-start 上的脚本标签(根据 的建议):

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

无文档的替代版本write/XHR --

   (() => { 
          'use strict';
          let needle = '/window.location/';
          if ( needle === '' || needle === '{{1}}' ) {
              needle = '.?';
          } else if ( needle.slice(0,1) === '/' && needle.slice(-1) === '/' ) {
              needle = needle.slice(1,-1);
          } else {
              needle = needle.replace(/[.*+?^${}()|[\]\]/g, '\$&');
          }
          needle = new RegExp(needle);
          const jsnode = () => {
                        try {
                            const jss = document.querySelectorAll('script');
                            for (const js of jss) {
                                if (js.outerHTML.match(needle)) {
                                        js.remove();
                                }           
                            }
                        } catch { }
          };
          const observer = new MutationObserver(jsnode);
          observer.observe(document.documentElement, { childList: true, subtree: true });
})();