Chris Weirup

Random ramblings

Limit Injected Script Scope for Safari App Extensions

Posted at — Apr 20, 2020

I’ve been working on a Safari App Extension in my spare time, specifically a web clipper for Joplin. I’ve never written a browser extension before (either the old style or new style for Safari), but it’s scratching my itch to build something useful with Swift.

One problem I had was that my content script was getting injected into every iframe on a page. Since my extension is designed to clip content from pages, this was having the unfortunate issue of clipping content from a bunch of iframes that I didn’t want.

For Chrome extensions, you can set a parameter to limit the injection to only the top frame or all frames. I was wracking my brain to figure out how to do this with Safari App Extensions. That is, until I RTFM.

There is no “global” parameter, but you can use this simple Javascript to limit what functions are used only in the top-most frame (i.e., no iframes):

if (window.top === window) {
	
}

And, yes, this is documented on Apple’s site. I’m only repeating here both to remind me and hopefully make it easier for others to find this information.

I do wish there was a more global setting similar to Chrome extensions, although I see the power of explicitly stating when and where certain code should not run depending on the frame.