想在谷歌扩展的Content Scripts里改写页面的window对象,例如
var _alert =window.alert;
window.alert = function(){
console.log(arguments);
_alert(arguments);
}
但是这个改写的并不是页面的window对象,而是Content Scripts里的window对象,请问页面的window对象在扩展里要如何获取和改写呢?
想在谷歌扩展的Content Scripts里改写页面的window对象,例如
var _alert =window.alert;
window.alert = function(){
console.log(arguments);
_alert(arguments);
}
但是这个改写的并不是页面的window对象,而是Content Scripts里的window对象,请问页面的window对象在扩展里要如何获取和改写呢?
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');
你可以尝试着试一下global,我在调试代码的时候发现在插件作用域中取不到页面的window(但是莫名其妙的可以取到document),然后我就尝试了一下global,发现这样就可以取到页面的window了,现在为止暂时还不知道是怎么回事……
10 回答11k 阅读
6 回答3k 阅读
5 回答4.7k 阅读✓ 已解决
4 回答3k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
記得好像不能直接存取
window
試試看~