Can a Web page communicate directly with a Safari extension on JavaScript level?
Ideally, I'd like some way to invoke the JavaScript in the extension's global page, but talking to the injected script will do, too, since that can talk to the global page via messages.
Direct function calling doesn't work. The window
object the page and the injected script have are distinct. safari.self
is not available to a regular Web page. Is there dispatchMessage
in some other DOM object that's visible to the Web page code?
Found one clumsy workaround. The injected script and the page share the document
object. The injected script would create an HTML element in the page (an <input type="hidden">
in my case), give it an agreed-upon ID, and hook its onclick
. The page would find that element by ID and invoke onclick
, passing some arguments along. The injected script gets control. For script-to-page callbacks, I'd use onchange
on the same element.
The calls are synchronous, even.
The injected script would then pass the message on to the extension's global page using safari.self.tab.dispatchMessage()
.