在插件上下文中访问 contentScript 变量,反之亦然?
这可能是同一部分下“内容脚本内无法识别的变量”的重复项。我从该问题的答案中解决了部分问题。是的,我明白
内容脚本上下文与插件脚本上下文完全断开。内容脚本在文档上下文中运行,而插件脚本则不然。
但这是否意味着我们永远无法在插件脚本上下文中访问内容脚本上下文中的变量?如果我们可以通过任何方式访问它们,请告诉我。我的要求需要将对象作为参数发送到另一个脚本(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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法直接从插件脚本上下文直接访问内容脚本中的变量。 将变量从内容脚本传递回附加组件,
您可以使用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.