如何在加载内容之前从页面中删除 <script>

问题描述 投票:0回答:1

我在服务器上托管了一个页面,该页面将一小部分脚本注入到我的index.html页面(https://my.f5.com/manage/s/article/K13849),我想删除此脚本在它运行之前。 简化的例子看起来像这样

<!doctype html>
<html lang="en">
<body> 
<script id="removeme">
    console.log("go");
</script>
</body>
</html>

我想阻止 'console.log("go");'以免被处决。 我尝试添加一个删除

removeme
脚本的脚本:

<!doctype html>
<html lang="en">
<body>
nothing to show
<script id="script_which_removes_the_other_script">
    // First attempt
    console.log("1 trying to remove " );
    const unwantedScript = document.getElementById('removeme');
    console.log("1 the script tag to remove: " + unwantedScript );
    if (unwantedScript) {
        unwantedScript.remove();
        console.log('1 Unwanted script removed.');
    }
    else{
     console.log('1 Did not found the script to remove.');
    }

    // Second attempt
    document.addEventListener('DOMContentLoaded', () => {
        console.log("2 trying to remove " );
        const unwantedScript = document.getElementById('removeme');
        console.log("2 the script tag to remove: " + unwantedScript );
        if (unwantedScript) {
            unwantedScript.remove();
            console.log('2 Unwanted script removed.');
        }
     });
</script>
<script id="removeme">
    console.log("go");
</script>
</body>
</html>

但是块 1 和块 2 都不能阻止该方法的运行。 控制台输出如下:

1 trying to remove 
1 the script tag to remove: null
1 Did not found the script to remove.
go
2 trying to remove 
2 the script tag to remove: [object HTMLScriptElement]
2 Unwanted script removed.

如何阻止

removeme
块中的函数运行?

javascript html dom
1个回答
0
投票

尝试更激进的方法,在 DOM 中创建脚本元素后立即将其删除。

这是我的方法,希望对你有帮助。将以下代码添加到第一个脚本标签中:


    console.log("Attempting to remove the unwanted script.");

    // Observe the document for any changes
    const observer = new MutationObserver(mutations => {
      mutations.forEach(mutation => {
        mutation.addedNodes.forEach(node => {
          if (node.nodeType === 1 && node.tagName === 'SCRIPT' && node.id === 'removeme') {
            node.remove(); // Remove the unwanted script
            console.log('Unwanted script removed.');
          }
        });
      });
    });

    // Start observing the document
    observer.observe(document.body, { childList: true, subtree: true });

    // Optionally disconnect the observer after some time or under certain conditions
    setTimeout(() => observer.disconnect(), 5000);
© www.soinside.com 2019 - 2024. All rights reserved.