Inject a script that you've written from a Safari App Extension into a webpage.
After you've written a script that can read and modify browser content, you need to add it to your Safari App Extension and apply it to webpages, where it can perform the defined actions and change the appearance and behavior of the webpages.
A script can apply to a single webpage, all webpages, or only some webpages—for example, webpages from certain domains. For your script to be injected, you must specify either Some or All website access for your app extension. For details, see Access and Permissions. For more about injected scripts, see About Injected Style Sheets and Scripts.
Add a Script
After specifying website access, add the script to your Safari App Extension.
Add the script files to your extension’s Xcode target.
SFSafarikey to the
NSExtensionelement in your extension’s
Infofile. The value for this key is an array of dictionaries.
For each script file, add a dictionary to the array. Each dictionary must have a
Scriptkey whose value specifies the path (relative to the Resources directory of the bundle) to the script file to include.
If your app extension specifies multiple scripts to be injected into the webpage, the scripts are executed in the order in which they appear in the
Access Resources Within Your App Extension’s Bundle
Resources stored in your app extension’s bundle can be accessed from within your scripts. Create a URL at runtime that references the resource relative to the root of the app extension’s bundle. The
safari property specifies the location of the bundle’s resource directory.
The code snippet below demonstrates how to use this property. This code adds a new image element to the webpage. The image is stored inside the Resources folder and referenced at runtime.
Execute Your Code After the Webpage Loads
The injected scripts are executed before the webpage has been fully loaded, so you can take action as resources are added to the webpage. During that time,
null. To take action after the document has been loaded, listen for the
DOMContent event. The code snippet below registers a document event handler to be called after the content is loaded.
Add an Element to the Webpage
The example code snippet below injects a new element into the webpage after the webpage loads. This example uses a resource stored in the bundle and shows how to register the document event handler.