Safari 扩展中的同步消息传递

发布于 2024-09-09 06:36:43 字数 153 浏览 1 评论 0原文

我正在开发一个 safari 扩展,我想知道是否有一种方法可以在 safari 扩展中进行同步消息传递。

我想从注入的 javascript 向全局页面发送一条消息,让注入的 javascript 等待返回结果。必须将我的代码拆分为另一个从全局页面接收消息的函数似乎过于复杂。

I'm working on a safari extension and I was wondering if there is a way to do synchronous message passing in a safari extension.

I want to send a message from my injected javascript to the global page have the injected javascript wait until a result is returned. Having to split my code into another function that receives a message from the global page just seems overly complicated.

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

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

发布评论

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

评论(2

波浪屿的海角声 2024-09-16 06:36:43

您可以使用“特殊”canLoad 消息。从技术上讲,它的目的是发送一条消息并返回一个与页面上的元素是否可以加载相关的值,但它实际上只是一条同步消息,由全局 HTML 页面以与其他任何页面相同的方式应答。您只需查找名为 'canLoad' 的消息,而不是传递自定义消息名称:

// injected script
var myVar = safari.self.tab.canLoad( event );

// global HTML file
<!DOCTYPE html>

<script type="text/javascript" charset="utf-8">
  safari.application.addEventListener( 'message', listen, true );

  function listen( msgEvent ) {
    switch( msgEvent.name ) {
      case 'canLoad':
        msgEvent.message = 'My return value';
        break;
    }
  }
</script>

您可以阅读有关 canLoad 消息在开发指南中。

You can use the "special" canLoad message. Technically, it's intended to send a message and return a value related to whether an element on the page can load, but it's really just a synchronous message that's answered by the global HTML page the same way as any other. You'd just look for the message named 'canLoad' instead of passing a custom message name:

// injected script
var myVar = safari.self.tab.canLoad( event );

// global HTML file
<!DOCTYPE html>

<script type="text/javascript" charset="utf-8">
  safari.application.addEventListener( 'message', listen, true );

  function listen( msgEvent ) {
    switch( msgEvent.name ) {
      case 'canLoad':
        msgEvent.message = 'My return value';
        break;
    }
  }
</script>

You can read more about the canLoad message in the development guide.

燃情 2024-09-16 06:36:43

还有人在 Safari 开发者论坛上问了同样的问题。简而言之,你不能。 (此外,在我看来,canLoad 函数纯粹是愚蠢的。)

但是,您可以使用闭包使其尽可能轻松。

There was someone else who asked the same question on the Safari developer forum. In short, you can't. (Besides, in my humble opinion, the canLoad function is purely stupid.)

You may, however, use closures to make it as painless as possible.

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