想在谷歌扩展的Content Scripts里改写页面的window对象,例如
var _alert =window.alert;
window.alert = function(){
console.log(arguments);
_alert(arguments);
}
但是这个改写的并不是页面的window对象,而是Content Scripts里的window对象,请问页面的window对象在扩展里要如何获取和改写呢?
你可以试试top.window.alert
看起来应该是这么回事
記得好像不能直接存取 window
var script = document.createElement("script");
script.innerHTML = 'var _alert = window.alert;window.alert = function(){console.log(arguments);_alert(arguments);}'
document.head.appendChild(script)
試試看~
content scripts跟你页面的脚本作用域是分开的,不能直接交互,看这里:https://developer.chrome.com/...
但是页面的DOM却是共享的,所以你可以通过插入向页面插入脚本的方式来修改页面window对象。
在你的manifest.json加入脚本代码权限:
"web_accessible_resources" : ["/js/my_file.js"],
在content scripts里面插入需要注入的脚本:
function injectScript(file, node) {
var th = document.getElementsByTagName(node)[0];
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', file);
th.appendChild(s);
}
injectScript( chrome.extension.getURL('/js/my_file.js'), 'body');