gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:52:57 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com