To be honest it's probably just easier to have different code in your popover and injected scripts. If you really want, you could do something like this:
function dispatchMessage(name, message) {
if (safari.self.tab) {
safari.self.tab.dispatchMessage(name, message);
} else if (safari.extension.globalPage.contentWindow) {
safari.extension.globalPage.contentWindow.handleMessage({name: name, message: message});
}
}
Then just use dispatchMessage('foo', 'bar')
in both your popover and injected scripts. It's a bit hacky though, because the message event object normally has more information on it than just the name
and message
, and you have to ensure that your handleMessage
function is actually the same function that is assigned as the message
event listener in the global page.