gpt4 book ai didi

javascript - 使用 unsafeWindow 通过 Greasemonkey 插入多个 javascript 函数时出现问题

转载 作者:行者123 更新时间:2023-12-02 20:17:30 25 4
gpt4 key购买 nike

问题是这些函数似乎无法互相看到。

例如:

unsafeWindow.helloworld = function() {

alert('Hello world!');

helloworld2();//fails with error saying it does not exist
}

unsafeWindow.helloworld2 = function() {

alert('Hello world!2');

helloworld();//fails with error saying it does not exist
}

insert("helloworld();"); //appends a script element to the body

这两个函数都可以使用 insert 或 firebug 控制台调用,但它们在内部并不了解彼此?这里有什么问题吗?

最佳答案

如果您格式化代码将会有很大帮助:

> unsafeWindow.helloworld = function() {
>
> alert('Hello world!');
>
> // fails with error saying it does not exist
> helloworld2();
> }
>
> unsafeWindow.helloworld2 = function() {
>
> alert('Hello world!2');
>
> //fails with error saying it does not exist
> helloworld();
>
> }

你有一个无限递归函数 - helloworld 调用helloworld2,它又调用helloworld,所以无限

但无论如何,您正在设置属性 unsafeWindow :

unsafeWindow.helloworld = function() {

但随后尝试使用在作用域链上解析的非限定标识符来调用它:

[... later, in helloword2 ...]

helloworld();

因此,标识符 helloworld 在调用 unsafeWindow.helloworld2 时创建的执行/变量对象的范围链上解析。

因此 helloworld 被设置为 unsafeWindow属性。当调用该函数时,将使用该函数的范围链解析标识符helloworld2

在浏览器中,窗口/全局对象位于作用域链上,因此可以在那里找到变量名称(即,如果在作用域链中没有更快找到,变量可能会解析为全局对象的属性),但我怀疑当 unsafeWindow.helloworld被调用,其作用域链以文档的全局对象结束,而不是 unsafeWindow 。否则,对文档中函数的调用也会在其作用域链上包含 unsafeWindow,这对我来说似乎不正确。

或者我的想法可能完全错误。 :-)

关于javascript - 使用 unsafeWindow 通过 Greasemonkey 插入多个 javascript 函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6053130/

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