我认为content_scripts是在页面上执行的,但现在好像有一些沙盒正在进行。
我正在开发一个扩展来记录站点的所有XHR流量(用于调试和其他开发目的),并且在控制台中,以下嗅探代码可以工作:
var o = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(){
console.log(arguments, 'open');
return o.apply(this, arguments);
};
console.log('myopen');
console.log(window, window.XMLHttpRequest, window.XMLHttpRequest.prototype, o, window.XMLHttpRequest.prototype.open);
每次发送XHR时都会记录一条消息。然而,当我把它放在扩展中时,真正的原型不会被修改。显然我的脚本看到的window.XMLHttpRequest.prototype与实际页面的不同。
有什么方法可以解决这个问题吗?此外,这个沙箱行为是否记录在任何地方?我环顾四周,但找不到任何东西。
答案 0 :(得分:8)
虽然Chrome的内容脚本位于“孤立的世界”中,但您可以通过在dom中插入脚本元素来完成类似于您所要求的内容。
作为概念验证,我使用了TamperMonkey Chrome扩展程序并创建了此脚本:
// ==UserScript==
// @name Modify Secret
// @namespace http://your.homepage/
// @version 0.1
// @description enter something useful
// @author You
// @match https://*/*
// @match http://*/*
// @grant none
// ==/UserScript==
console.log(secret);
var el = document.createElement('script');
el.innerHTML = 'secret = "the blue dog"';
document.body.appendChild(el);
然后我导航到运行此javascript的http://s.codepen.io/boomerang/745009c49e60974cf9dba1b070f27d111458064000840/index.html:
var secret = 'the brown fox';
var secretPrinter = setInterval(function () {
console.log(secret);
}, 1000);
如果你检查控制台,人们会看到不断打印出“棕色狐狸”,而是“蓝狗”。
一般来说,我认为浏览器试图实现的安全概念是防止页面环境访问内容脚本的环境。意识到,使用浏览器扩展可以完成类似的工作并不奇怪。
答案 1 :(得分:6)
你做不到。根据{{3}}:
但是,内容脚本有一些 限制。他们不能:
- 使用chrome。* API(chrome.extension的部分除外)
- 使用其扩展程序页面定义的变量或函数
- 使用由网页或其他内容脚本定义的变量或函数
- 制作跨网站XMLHttpRequests