2017-04-16 86 views
2

我想建立一个Chrome扩展;这方面的经验最少。我跟着Insert code into the page context using a content script使用第一种方法将js代码注入页面。覆盖铬扩展中的JavaScript警报

我想建立一个js框架而不是别人的代码,它严重依赖于打破我的覆盖层功能的警报,所以我只是想让他们沉默 - 实际上,我宁愿通过将消息发送到console.log中,但我会在现阶段采取我所能得到的。所以我试着按照JavaScript: Overriding alert()设置我的最终js文件(nogo.js)进行注入。

nogo.js被注入,但它似乎没有抑制警报的效果。可能是因为另一个html文件本身是由一个不同的js文件启动的,注入的速度太慢或者是乱序?

的manifest.json

"content_scripts": [ 
     { 
      "matches": ["*://URL/*"], 
      "js": ["myscript.js"], 
      "run_at": "document_end", 
      "all_frames": true 
     }, 
     { 
      "matches": ["*://URL/*"], 
      "js": ["noalerts.js"], 
      "run_at": "document_start", 
      "all_frames": true 
     } 

     ], 
     "web_accessible_resources": ["script.js","nogo.js"] 

    } 

myscript.js

var s = document.createElement('script'); 
// TODO: add "script.js" to web_accessible_resources in manifest.json 
s.src = chrome.extension.getURL('script.js'); 
s.onload = function() { 
    this.remove(); 
}; 
(document.head || document.documentElement).appendChild(s); 

noalerts.js

var n = document.createElement('script'); 
// TODO: add "script.js" to web_accessible_resources in manifest.json 
n.src = chrome.extension.getURL('nogo.js'); 
n.onload = function() { 
    this.remove(); 
}; 
(document.head || document.documentElement).appendChild(n); 

nogo.js

window.alert = null; 
+0

感谢您的提示,我已经能够得到nogo.js注入,但不幸的是代码不能防止警报窗口。 – CursingLoudlyintheOffice

+0

这里:https://stackoverflow.com/q/12095924/632951 – Pacerier

回答

2

为了使alert什么也不做,只是贴线来覆盖它:

var s = document.createElement('script'); 
s.innerHTML = "alert = function(){}" 
document.body.appendChild(s); 

的功能将被重新声明你的函数体。我不得不在我的扩展中做类似的事情。

通过类比可以使confirm功能说“是”每次:

var s = document.createElement('script'); 
s.innerHTML = "confirm= function(){return true;}" 
document.body.appendChild(s); 

这可以用于最简单的情况。例如,没有人做其他别的页面,等上

注意事项:您可以通过将代码粘贴到控制台并尝试调用alert来尝试此方法。 注意2:代码可以在内容脚本中执行,因为它在其脚本和内容脚本之间共享的文档。