Learn how you can affect the appearance or behavior of a webpage by using injected style sheets and scripts.
Framework
- Safari
Services
Overview
To add or override styles and behaviors in a webpage, you write style sheets and scripts that you then inject into your webpage to read and modify its content.
Injected Style Sheets
Injected style sheets are treated like user style sheets, as defined by the W3C. Styles are added in the following order:
Your Safari App Extension styles
The webpage author's styles
The webpage author's styles that are declared as
!important
Your Safari App Extension styles that are declared as
!important
At each stage, a new definition overrides any previous definition. Style properties in your injected style sheets are added to existing page style properties, but your styles don’t override existing page styles unless you declare the new ones as !important
.
For example, adding the following styles overrides a website using colored text on a colored background and sets it to black text on a white background for a particular element:
span.anElement {
color:black;
background:white;
}
Injected Scripts
You can inject .js
files (text files that contain JavaScript functions and commands) into a webpage. The scripts in these files have access to the DOM of the webpages they’re injected into. They have the same access privileges as scripts executed from a webpage’s host. Injected scripts are loaded each time a webpage is loaded, so you should keep them lightweight.
Scripts are injected into the top-level page and any child pages with HTML sources, such as iframes. Don’t assume that there’s only one instance of your script per browser tab. If you don’t want your injected script to execute inside iframes, preface your high-level functions with a test, as shown in this example:
if (window.top === window) {
// The parent frame is the top-level frame, not an iframe.
// All non-iframe code goes before the closing brace.
}
Injected scripts have an implied namespace—you don’t have to worry about your variable or function names conflicting with those of the website author, nor can a website author call functions in your extension. In other words, injected scripts and scripts included in the webpage run in isolated worlds, with no access to each other’s functions or data.