我创建了一个脚本,该脚本阻止了在json数组中定义的脚本。
但是当我加载的脚本数量超过2个时,阻塞将不再起作用。
任何人都可以告诉我我的错误是什么,或者给我一个提示,让我可以使其与多重脚本一起工作。
这阻止了Google Recaptcha脚本:
<script>
function blockScript(origin) {
const scripts = Array.from(document.getElementsByTagName("SCRIPT"));
if (scripts.length > 0) {
scripts.forEach((script) => {
if (script.src.includes(origin)) {
document.head.removeChild(script);
}
})
}
}
</script>
<script>
var json = [
{
"name" : "Google Recaptcha",
"url" : "www.google.com",
"desc" : "Recaptcha",
"rights": ""
}];
const observer = new MutationObserver((mutationsList, observer) => {
for(let mutation of mutationsList) {
const addedNodes = Array.from(mutation.addedNodes);
if (addedNodes && addedNodes.some(n => n.nodeName === 'SCRIPT')) {
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.url);
blockScript(obj.url);
}
}
observer.disconnect();
}
});
observer.observe(document, { childList: true, subtree: true });
</script>
<script src="https://www.google.com/recaptcha/api.js?render=MYKEY"></script>
这不是。
<script>
function blockScript(origin) {
const scripts = Array.from(document.getElementsByTagName("SCRIPT"));
if (scripts.length > 0) {
scripts.forEach((script) => {
if (script.src.includes(origin)) {
document.head.removeChild(script);
}
})
}
}
</script>
<script>
var json = [
{
"name" : "Google Recaptcha",
"url" : "www.google.com",
"desc" : "Recaptcha",
"rights": ""
}];
const observer = new MutationObserver((mutationsList, observer) => {
for(let mutation of mutationsList) {
const addedNodes = Array.from(mutation.addedNodes);
if (addedNodes && addedNodes.some(n => n.nodeName === 'SCRIPT')) {
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.url);
blockScript(obj.url);
}
}
observer.disconnect();
}
});
observer.observe(document, { childList: true, subtree: true });
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://www.google.com/recaptcha/api.js?render=MYKEY"></script>
谢谢!
答案 0 :(得分:1)
删除断开连接方法将解决此问题,并且也应考虑延迟加载的脚本。