我到处试图找到这个问题的答案。 我希望我的扩展能够禁用页面上的所有javascript但允许插入一个有效的脚本。 (所以chrome.contentSettings.javascript现在不是一个有效的选项) 或者我想要一种方法来删除所有脚本标签之前任何一个标签(这有点相同)
我尝试将内容脚本插入runat:document_start但当时dom并不完全存在。 itried在tabs.onUpdate上添加了一个竞争对手,当状态正在加载但是为时已晚,以及document_end中的内容脚本(所有这些都试图删除脚本标记),但现在还为时已晚。 在绝望的行为中,我试图改变element.innerHTML的getter和setter的行为。删除标签但不起作用
我试图避免向location.href发送xhr请求并解析和重新设置内容,因为这太过密集。
任何想法?
答案 0 :(得分:6)
在看到您的评论后,我认为这可能满足您的需求。它的工作原理是获取页面源,将其渲染为dom,禁用所有j,然后将其放回页面。不完全是你想要的,但应该很好地适应你的情况...
mainfest.json
{
"name": "Reload and Kill JS - Using a content script",
"version": "1.0",
"permissions": [
"tabs", "<all_urls>" , "storage"
],
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["injectedCode.js"],
"run_at" : "document_start"
}
],
"minimum_chrome_version" : "20",
"manifest_version" : 2
}
<强> background.js 强>
chrome.storage.local.set({"blockhttp://paez.kodingen.com/":true});
injectCode.js
reloadAndKillJS = function() {
document.documentElement.innerHTML = 'Reloading Page...';
var xhr = new XMLHttpRequest();
xhr.open('GET', window.location.href, true);
xhr.onerror = function() {
document.documentElement.innerHTML = 'Error getting Page';
}
xhr.onload = function() {
var page = document.implementation.createHTMLDocument("");
page.documentElement.innerHTML = this.responseText;
var newPage = document.importNode(page.documentElement, true);
var nodeList = newPage.querySelectorAll('script');
for (var i = 0; i < nodeList.length; ++i) {
var node = nodeList[i];
if (node.src) {
node.setAttribute('original-src', node.src);
node.removeAttribute('src');
}
node.innerText = '';
}
document.replaceChild(newPage, document.documentElement);
delete page;
// Do your thing here
}
xhr.send();
}
chrome.storage.local.get("block"+window.location.href,function(items){
if (items["block"+window.location.href]){
window.stop();
reloadAndKillJS();
}
});
答案 1 :(得分:1)
嗯,真正防止脚本的唯一方法是使用contentSettings。因此,您需要将代码放在其他域中,因为contentSettings规则可以应用于特定的URL。
将内容脚本放在文档启动时运行。
<强> contentScript.js:强>
window.stop();
document.all[0].innerHTML = "\
<html>\
<body>\
<iframe src=\"chrome-extension://ID/inject.html?url="+encodeURIComponent(location.href)+"\"></iframe>\
</body>\
</html>";
<强> inject.html:强>
<html>
<head>
<script>
var frame = document.querySelector('iframe');
frame.src = location.search.replace('?url=', '');
frame.onload = function() {
//Your stuff here
}
</script>
</head>
<body>
<iframe></iframe>
</body>
<html>
现在您的代码位于父框架和另一个域中,但它可能会导致一些CORS问题,您可以尝试稍后找到一些解决方法。 试一试,然后告诉我是否有什么需要解决的。