Safari 扩展程序将消息发送到特定选项卡 [英] Safari extension send message to a specific tab

查看:62
本文介绍了Safari 扩展程序将消息发送到特定选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将消息从全局页面发送到特定标签?
我目前正在做的是,在创建选项卡时,注入的脚本会创建一个唯一的 ID,并将带有此编号的消息发送到全局页面,全局页面会保存此编号.
如果全局页面需要向标签发送一些数据(即:标签 #3),则全局页面将向所有标签广播"消息,编号为 #3 作为传递给选项卡的数据的一部分(遍历所有选项卡并向每个选项卡发送消息).
是否有类似 Chrome 的东西:(即:chrome.tabs.sendRequest(tabID, {action: 'respond', params:[channel,msg,async]});)?

Is there a way to send a message from the global page to a specific tab?
What I'm currently doing is, on tab creation the injected script creates a unique id and sends a message with this number to the global page and the global page saves this number.
If the global page needs to send some data to a tab (i.e: tab #3) then the global page will "broadcast" a message to all tabs with the number #3 as part of the data passed to the tabs (iterate over all tabs and send a message to each tab).
Is there something like Chrome: (i.e: chrome.tabs.sendRequest(tabID, {action: 'respond', params:[channel,msg,async]});)?

现在我正在做的是在注入的脚本端,每个脚本都有一个监听器来捕捉这个消息.如果内容脚本唯一编号等于全局页面发送的编号,则此消息是给它的,否则 doNothing.

Right now what I'm doing is that on the injected script side, each script has a listener that will catch this message. If a content script unique number is equal to the number sent by the global page then this message is for it, else doNothing.

在 Safari 中是否有更简单更优雅的方法来做到这一点?

Is there an easier more elegant way to do this in Safari?

推荐答案

在全局页面的消息事件处理程序中,event.target 指的是从中接收消息的选项卡.例如:

Within the global page's message event handler, event.target refers to the tab from which a message was received. For example:

function handleMessage(e) {
    if (e.name === 'whatIsMyUrl?') {
        e.target.page.dispatchMessage('yourUrlIs', e.target.url);
    }
}
safari.application.addEventListener("message", handleMessage, false);

Safari 扩展 API 没有选项卡 ID,但您可以将每个选项卡保存在关联数组中,并在以后使用其索引进行寻址.例如:

The Safari extension API doesn't have tab IDs, but you could just keep each tab in an associative array and use its index to address it later. For example:

function handleMessage(e) {
    if (e.name === 'hereIsMyId') {
        myTabs[e.message] = e.target;
    }
}
safari.application.addEventListener("message", handleMessage, false);

// later...
myTabs[someId].page.dispatchMessage('haveSomeCake');

这篇关于Safari 扩展程序将消息发送到特定选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆