如何从 contentURL 发送 JSON 对象:data.url(“foo.html”) 到 contentScript

发布于 2025-01-02 11:37:02 字数 99 浏览 4 评论 0原文

我尝试使用 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 技术交流群。

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

发布评论

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

评论(2

酒几许 2025-01-09 11:37:02

只需使用 JSON.stringify() 将对象转换为字符串:

var data = {a: 1, b: 2};
window.postMessage(JSON.stringify(data), "*");

在另一端使用 JSON.parse() 来反转该过程:

var data = JSON.parse(message);

Simply use JSON.stringify() to turn the object into a string:

var data = {a: 1, b: 2};
window.postMessage(JSON.stringify(data), "*");

On the other end use JSON.parse() to reverse the process:

var data = JSON.parse(message);
旧时光的容颜 2025-01-09 11:37:02

如果您使用:

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?

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