首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >防止执行特定内联脚本标记

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

Stack Overflow用户
提问于 2018-04-25 11:15:01
回答 2查看 2.3K关注 0票数 8

我试图为坦帕猴编写一个脚本,以防止执行特定的内联脚本标记。页面的正文如下所示

代码语言:javascript
复制
<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>

我试图使用我的script脚本删除跑到标记,但是如果我使用跑到 document-startdocument-body,则script标记还不存在。如果我在document-enddocument-idle上运行它,我想要删除的script标记将在执行document-idle脚本之前运行。

如何防止script标记的执行?

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

版本:

  • 铬65.0.3325.181
  • 坦佩猴子4.5
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-08-05 06:16:56

没有doc.write/XHR的替代版本--

代码语言:javascript
复制
   (() => { 
          '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 });
})();
票数 1
EN

Stack Overflow用户

发布于 2018-04-25 13:53:46

删除document-start上的脚本标记(按照wOxxOm的建议):

代码语言:javascript
复制
(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();
})();
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50020880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档