首页 > 解决方案 > 阻止执行特定的内联脚本标签

问题描述

我正在尝试为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,但如果我运行它 document-start或标签尚不存在。如果我运行它或者我想删除的标签在我的 Tampermonkey 脚本执行之前运行。document-bodyscriptdocument-enddocument-idlescript

如何防止script标签的执行?


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


版本:

标签: javascripthtmltampermonkey

解决方案


删除脚本标记document-start(如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();
})();

推荐阅读