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

标签 javascript google-chrome userscripts content-script

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

var smilies = false;

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

unsafeWindow.smilies = true;

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

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

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

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

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on.

这是关于 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);

最佳答案

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

关于javascript - 使用 Chrome 的用户脚本劫持变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10485992/

相关文章:

javascript - 如何发出 jQuery JSON 请求并使用响应数据更改 html 元素值?

css - 为什么 Chrome Dev Tools 不显示 "computed"选项卡?

javascript - 已选中 ="checked"未在 Chrome 中呈现为选中的单选按钮

javascript - 将 Javascript 对象保存到 Chrome.Storage

greasemonkey - 更多资源密集型 : Tampermonkey script (for video control) running on ALL domains—or just 1K domains each with its own @include entry?

javascript - 为什么配合插件调用vue组件方法失败?

javascript - 谷歌脚本超时

javascript - 离开页面 javascript/jquery

javascript - 如何防止一个用户脚本中附加的事件处理程序干扰另一用户脚本?

php - 如何在 PHP 中动态创建 UserScript?