使用Chrome的用户脚本劫持变量

Bad*_*ari 9 javascript google-chrome userscripts content-script

我正在尝试使用用户脚本更改页面中的变量.我知道在源代码中有一个变量

var smilies = false;
Run Code Online (Sandbox Code Playgroud)

从理论上讲,我应该能够改变它:

unsafeWindow.smilies = true;
Run Code Online (Sandbox Code Playgroud)

但它不起作用.当我试图警告或将变量记录到控制台而没有劫持时,我得到它是未定义的.

alert(unsafeWindow.smilies); // undefined !!!
Run Code Online (Sandbox Code Playgroud)

编辑:如果它改变了什么,我正在使用Chrome ...

http://code.google.com/chrome/extensions/content_scripts.html说:

内容脚本在称为孤立世界的特殊环境中执行.他们可以访问注入页面的DOM,但不能访问页面创建的任何JavaScript变量或函数.它将每个内容脚本视为在其运行的页面上没有执行其他JavaScript.

这是关于Chrome扩展,但我猜这与用户脚本也是一样的?

谢谢你,Rob W.所以需要它的人的工作代码:

var scriptText = "smilies = true;";
var rwscript = document.createElement("script");
rwscript.type = "text/javascript";
rwscript.textContent = scriptText;
document.documentElement.appendChild(rwscript);
rwscript.parentNode.removeChild(rwscript);
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 25

内容脚本(Chrome扩展)中,页面的全局window对象与内容脚本的全局对象之间存在严格的分离.

最终的Content脚本代码:

// This function is going to be stringified, and injected in the page
var code = function() {
    // window is identical to the page's window, since this script is injected
    Object.defineProperty(window, 'smilies', {
        value: true
    });
    // Or simply: window.smilies = true;
};
var script = document.createElement('script');
script.textContent = '(' + code + ')()';
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
Run Code Online (Sandbox Code Playgroud)