在插件上下文中访问 c​​ontentScript 变量,反之亦然?

发布于 2025-01-02 19:32:11 字数 377 浏览 3 评论 0原文

这可能是同一部分下“内容脚本内无法识别的变量”的重复项。我从该问题的答案中解决了部分问题。是的,我明白

内容脚本上下文与插件脚本上下文完全断开。内容脚本在文档上下文中运行,而插件脚本则不然。

但这是否意味着我们永远无法在插件脚本上下文中访问内容脚本上下文中的变量?如果我们可以通过任何方式访问它们,请告诉我。我的要求需要将对象作为参数发送到另一个脚本(data/utilities.js)中的函数,并可能获取返回的对象。做前者没有困难,但由于上述上下文问题,我陷入了后者。我能够从内容脚本上下文返回值,但无法在插件上下文中访问相同的值。谁能帮我举一个小例子吗?

PS 我也可以在那里讨论它,但我读到我不应该,因为这不是一个讨论论坛。

This one's perhaps a duplicate of "variable not recognized inside contentscript" under the same section. I got part of my query solved there from the answer to that question. Yeah, I understand that

The content script context is entirely disconnected from the addon script context. Content scripts are run in the context of the document, while addon scripts aren't.

But does that mean we can never access a variable in the content script context in the addon script context? If by any means we could access them, please do let me know. My requirement needs objects to be sent as parameters to functions in another script(data/utilities.js) and possibly get the returned object. There was no difficuty in doing the former but am stuck with the latter cos of the aforementioned context problem. I am able to return the value from the content script context but unable to access the same in the addon context. Can anyone please help me out with a little example of this?

PS I could as well discussed it there but I read that I shouldn't as this ain't a discussion forum.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如若梦似彩虹 2025-01-09 19:32:11

您无法直接从插件脚本上下文直接访问内容脚本中的变量。 将变量从内容脚本传递回附加组件,

您可以使用self.port.emit('send-some-var', some_var)

然后您将收到通过侦听同一事件来获取附加脚本中的变量值:

worker.port.on('send-some-var', function(data) { console.log(data) })

然而,主要的限制是传递的数据必须是 JSON 可序列化的,所以你不能有一个带有方法等的复杂对象。只有数据。

You cannot get direct access to variables in the content script from the addon script context directly. You can pass the variable back to the add-on from the content script using

self.port.emit('send-some-var', some_var)

You would then receive the variable's value in the add-on script by listening for the same event:

worker.port.on('send-some-var', function(data) { console.log(data) })

The main limitation however is that the data being passed through must be JSON-serializable, so you could not have a complex object with methods, etc. Only data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文