-1

我的网站上有一个代码

<script type="text/javascript" async="" src="https://example.js"></script>

我希望不要执行此脚本。我无法从页面中手动删除它,我可以添加 html 和 js 代码。我在网站上有其他外部脚本,所以我不能全部屏蔽它们。如何阻止/删除此脚本?

4

1 回答 1

0

最优雅的解决方案可能是进入您的服务器配置并设置内容安全策略以仅将您希望允许在您的页面上运行的脚本列入白名单。这不仅可以解决您的问题,而且一般来说,禁止浏览器执行来自不可靠来源的脚本也是一种很好的做法,以防万<script src一不小心包含了错误。

缺少这一点,也可以<script>使用 Javascript 删除标签,方法是在错误脚本运行之前附加一个 MutationObserver:

<script>
new MutationObserver((mutations, observer) => {
  for (const mutation of mutations) {
    for (const addedNode of mutation.addedNodes) {
      // Test if the addedNode is the script tag you want to remove
      // Insert whatever logic is required here
      if (addedNode.tagName === 'SCRIPT') {
        addedNode.remove();
        // Disconnect the observer, it's not needed anymore
        observer.disconnect();
      }
    }
  }
  
})
  .observe(document.body, { childList: true });
</script>

<script>
  alert('evil script to remove');
</script>

<script>
  console.log('a non-evil script');
</script>

(但这通常是 X/Y 问题的 X 解决方案)

于 2020-04-21T09:42:04.113 回答