问题描述
我正在编写一个Javascript代码,该代码需要监视新的'script'元素并阻止一些已知源。
要捕获这些错误,我尝试使用 MutationObserver 和__ definesetter __, 两者都可以监视'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
});
解决方法
您可以使用Service workers来拦截网络请求。这样的事情应该可以解决问题:
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' }));
}
});