【问题标题】:Hijacking a variable with a userscript for Chrome使用 Chrome 的用户脚本劫持变量
【发布时间】:2012-05-16 04:36:07
【问题描述】:

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

var smilies = false;

理论上我应该可以这样改:

unsafeWindow.smilies = true;

但它不起作用。当我尝试在不劫持的情况下向控制台发出警报或将变量记录到控制台时,我发现它是未定义的。

alert(unsafeWindow.smilies); // undefined !!!

编辑:如果 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);

【问题讨论】:

  • smilies 不是在函数内部声明的变量?
  • 不,它不在函数内部。
  • 对于更长的函数,使用自执行格式scriptText = '('+ fn +')();';,其中fn是扩展中的任何(可能很长)函数。

标签: javascript google-chrome userscripts content-script


【解决方案1】:

Content scripts(Chrome 扩展程序)中,页面的全局window 对象和内容脚本的全局对象之间有严格的分隔。

最终的内容脚本代码:

// 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);

【讨论】:

  • 感谢您非常详细的回答!!!我已经通过链接解决了我的问题(我相信是你,userscripts.org/scripts/review/121923)给了我。有趣的是,我不需要使用 Object.defineProperty 来使其工作,我想知道为什么... 编辑:好的,你也写过它。再次感谢!!!
  • @BadrHari Object.defineProperty 仅在您想防止变量被覆盖时才需要,as shown in this answer。目前,当您的脚本在页面的smiley 变量声明之前执行时,该变量将被页面覆盖。使用Object.defineProperty 可以防止这种情况发生。
  • @theonlygusti 这取决于。如果要在变量存在之前对其进行设置,请务必使用"run_at": "document_start"。如果你想在变量已经定义后覆盖它,使用"document_end""document_idle" 可能会起作用。
猜你喜欢
  • 2011-06-06
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 2011-06-04
  • 2013-04-27
相关资源
最近更新 更多