控制 DOM 中的每一个'src'属性更改



我正在编写一个Javascript代码,需要注意新的"script"元素,并阻止一些已知的源代码。

为了捕捉这些,我尝试使用MutationObserver和__defineSeter__,两者都可以监视"src"的更改,但只有在HTTP请求已经发送之后——所以即使我更改了src,它也不会真正被阻止。

window.HTMLScriptElement.prototype.__defineSetter__('src', function (d) 
{
console.log("HTMLScriptElement: ",d);
if (d.indexOf('localhost') != -1) {
//BLOCK SCRIPT
}
});
new MutationObserver(function (a) {
a.forEach((e) => {
e.addedNodes.forEach((z) => 
{
if (z.nodeName.toLowerCase() == "script" && z.src.indexOf('localhost') != -1) 
{
//BLOCK SCRIPT
}
})
})
}).observe(window.document, {
attributes: true,
childList:true,
subtree:true
});

您可以使用服务工作者来拦截网络请求。像这样的东西应该可以做到:

self.addEventListener('fetch', function (event) {
const blockedUrls = [
//...
];
if (blockedUrls.some(x => event.request.url.startsWith(x))) {
event.respondWith(new Response('blocked', { status: 401, statusText: 'Unauthorized' }));
}
});

最新更新