chrome extension 可以拿到并且改写页面的window对象吗?

想在谷歌扩展的Content Scripts里改写页面的window对象,例如

var _alert =window.alert;
window.alert = function(){
    console.log(arguments);
    _alert(arguments);
}

但是这个改写的并不是页面的window对象,而是Content Scripts里的window对象,请问页面的window对象在扩展里要如何获取和改写呢?

阅读 19.2k
4 个回答

記得好像不能直接存取 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');

你可以试试top.window.alert

clipboard.png

看起来应该是这么回事

你可以尝试着试一下global,我在调试代码的时候发现在插件作用域中取不到页面的window(但是莫名其妙的可以取到document),然后我就尝试了一下global,发现这样就可以取到页面的window了,现在为止暂时还不知道是怎么回事……

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏