Pass data back and forth between Safari App Extension and injected scripts.
The injected script and your Safari App Extension live in different sandboxed worlds, each with specific limits on what it can access. You can’t call directly from the native code in your app extension to the injected script running in the browser. However, some sort of communication between the two is almost always desirable. For example, you may have a toolbar or contextual menu item that you want to use to affect web content.
The solution is to pass messages between the injected script and the app extension. The two runtime environments share a common format for message passing, and each provides an interface for sending and receiving messages.
Within the scripting environment, you have access to the
document objects for the browser content as well as a
safari object. The
safari object is an instance of the
Safari class. It provides details about your app extension and support for passing messages between your injected script and the app extension.
This table describes your app extension’s key properties:
A proxy for the app extension. Use it to retrieve information about your app extension and pass messages to it.
A proxy for your injected script. Use it to install event listeners to respond to messages from your app extension.
Send Messages to the App Extension
The parameter for
dispatch is a string that identifies the message you want to send. You create your own message names and decide what those messages mean for your app extension.
You can optionally send additional user data to accompany the message:
For example, the following snippet sends an array in a message:
When the app extension receives the message, the extension handler’s
messagemethod is called. This method's parameters include the message name, the page that sent the message, and, if part of the message, a user dictionary:
Send Messages to the Injected Script
When the app extension needs to send a message to an injected script, it calls the
dispatch method on the target page:
The message is packaged as an event whose type is
"message". To respond to the message, the injected script must register an event listener for message events using
The event passed into the event handler is a
Safari object. Its
name property identifies the message, and its
message property contains the dictionary of user data:
The complete workflow is shown below.