Safari extension sends a message to a specific tab
Is there a way to send a message from a global page to a specific tab?
What I am currently doing is that when the tab is created, the injected script creates a unique id and sends a message with that number to the global page, and the global page stores that number.
If the global page needs to send some data to a tab (ie Tab #3
), then the global page will "broadcast" a message to all numbered tabs #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: (ie:) chrome.tabs.sendRequest(tabID, {action: 'respond', params:[channel,msg,async]});
?
What I'm doing now is that on the nested side of the script, each script has a listener that will catch this message. If the script's unique content number is equal to the number posted by the global page, this is the message to it, otherwise doNothing
.
Is there an easier way to do this in Safari?
source to share
In the message event handler, the global page event.target
refers to the tab from which the 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);
There are no tab identifiers in the Safari extension API, but you can simply store each tab in an associative array and use its index to reference 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');
source to share
Safari's answer
In your global page save directly in the tab .. so for example on the message from the injected script
// global page
safari.application.addEventListener("message", function(event){
switch(event.name){
case "saveData":
event.target.page.tabData = { data: myData }
break;
case "getData":
event.target.page.dispatchMessage("tabData", myData);
break;
}
}, false);
-
// injected page
// first save data
safari.self.tab.dispatchMessage("saveData", {firstname:"mike", age: 25} );
// setup listner to recevie data
safari.self.addEventListener("message", function(event){
switch(event.name){
case "tabData":
// get data for page
console.debug(event.message);
// { firstname: "mike", age: 25 }
break;
}
}, false);
// send message to trigger response
safari.self.tab.dispatchMessage("getData", {} );
source to share