如何从 contentURL 发送 JSON 对象:data.url(“foo.html”) 到 contentScript
我尝试使用 window.postMessage ,但这只会将变量(包含字符串)发送到 contentScript 。但我想发送一些变量的值。这似乎可以通过使用 JSON 对象来实现。
I tried using window.postMessage
but this only sends a variable (containing string) to the contentScript. But I want to send a number of variables' values. This seems to be possible by using a JSON object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用
JSON.stringify()
将对象转换为字符串:在另一端使用
JSON.parse()
来反转该过程:Simply use
JSON.stringify()
to turn the object into a string:On the other end use
JSON.parse()
to reverse the process:如果您使用:
self.port.emit('some-event', object)
...并且仅发送可以正确序列化为 JSON 的对象,SDK 将为您处理序列化和解析。下面是一个快速构建器示例,说明了这一点:
https://builder.addons.mozilla.org /addon/1036506/latest/
我原以为postMessage会是一样的?
If you use:
self.port.emit('some-event', object)
...and only send objects that can be serialized into JSON properly, the SDK will handle serialization and parsing for you. Here's a quick builder example that illustrates this:
https://builder.addons.mozilla.org/addon/1036506/latest/
I had thought that postMessage would be the same?