防止执行特定的内联脚本标记

时间:2018-04-25 11:15:02

标签: javascript html tampermonkey

我试图为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'。因此,在这种情况下防止重新加载也足够了。

版本:

  • Chromium 65.0.3325.181
  • Tampermonkey 4.5

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

没有doc.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 });
})();