Hi,
I'm developing an extension and I need to debug console logs that are logged in the Service Worker. The worker is configured in the manifest and is generally working as expected:
However, when I open the browser, go to any site, and open Develop -> Service Workers or Develop -> Web Extension Background Content it is not visible there, so I can't really access the logs:
But then I noticed that if I go out of focus from the browser for some time (and probably let the SW die), it becomes visible and I can open it without an issue:
So, a couple of questions:
Why isn't it instantly accessible? The extension Service Worker dev tools should be accessible regardless of what is happening to the tab or the browser, even if the SW terminates.
Why does it eventually appear under Web Extension Background Content instead of the Service Workers when it is in fact an SW?
Safari Extensions
RSS for tagEnhance and customize the web browsing experience on Mac, iPhone, and iPad with Safari Extensions
Posts under Safari Extensions tag
126 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I have a Safari App Extension which allows users to switch between last open tabs with a shortcut option+tab in the same way it's possible to switch between last open apps with command+tab.
Here is how i do it:
I inject a content script on all websites which has the only thing – key listener for option+tab presses.
When a user presses option+tab, that keyboard listener detects it and sends a message to the Safari Handler.
Then Safari Handler sends a message to the containing app and it shows a panel with last open tabs.
This approach has a problem: it shows a message to a user in settings: "Can read sensitive info from web pages, including passwords..."
Which is bad, because in reality i don't read passwords.
If i remove SFSafariContentScript key in the Safari App Extension target's Info.plist, then this message about reading sensitive data disappears, but then i loose the ability to open the tabs panel.
How can I open my app window with a shortcut without frightening a user?
It's possible to listen to global key presses, but that would require a user to grant the app permissions of Accessibility (Privacy & Security) in macOS system settings, which also sounds shady.
I know an app which does not require an Accessibility permission: https://apps.apple.com/ua/app/tabback-lite/id6469582909 and at the same time it does not tell a user about reading sensitive data in the extension settings.
Here is my app: https://apps.apple.com/ua/app/tab-finder/id6741719894 It's open-source: https://github.com/kopyl/safari-tab-switcher
In a project to create a web extension for Safari, using scripting.registerContentScript() API to inject a bunch of scripts into web pages, I needed to manage a dynamic whitelist (i.e., web pages where the scripts should not be injected).
Fortunately, scripting.registerContentScripts() gives you the option of defining a list of web pages to be considered as a whitelist, using the excludeMatches parameter in the directive, to represent an array of pages where the script should not be injected.
Here just a sample of what I mean:
const matches = ['*://*/*'];
const excludeMatches = ['*://*.example.com/*'];
const directive = {
id: 'injected-jstest',
js: ['injectedscript.js'],
matches: matches,
excludeMatches: excludeMatches,
persistAcrossSessions: false,
runAt: 'document_start'
};
await browser.scripting.registerContentScripts([directive])
.catch(reason => { console.log("[SW] >>> inject script error:",reason); });
Of course, the whitelist (the excludeMatches array) is not static, but varies over time according to the needs of the moment.
Everything works perfectly in Chromium browsers (Chrome, Edge, ...) and Firefox, but fails miserably in Safari. In fact, Safari seems to completely ignore the excludeMatches parameter and injects the script even where it should not.
Has anyone had the same problem and solved it somehow?
NOTE : To test the correctness and capabilities of the API in each browser, I created a simple repository on Github with the extension code for Chromium, Firefox and Safari (XCode project).
We are testing our safari web extension (https://apps.apple.com/us/app/whatfix-for-jnj-centris/id6723895659) on an iPad 7th Gen (iPadOS v - 17.4.1)
I am sharing a video link where you can see the widget (named Self Help) appears on the application. However after a couple of refreshes, it vanishes. This widget is powered by the extension.
We tried connecting the iPad to Mac and opened the webinspector. The extension content script sends a message to the service worker and it is expected to send back a response which it is not doing
We believe it is related to an issue that has been highlighted multiple times in the developer forum -
https://developer.apple.com/forums/thread/758346
We have tried using several workaorunds as suggested by peer developers in the thread but we are unable to revive the service worker once it is killed.
We would like to understand from you, how to recover from this issue. Is there any workaround that we can apply to make sure that extension works fine?
It would be immensely helpful if we can get on a call to explain the issue further
Video Link: https://www.icloud.com/iclouddrive/0a7NR7BzDQHHU8zCHERuySBMw#RPReplay%5FFinal1740034010
My app is a Safari extension. When trying to validate the app, I get the following error:
App sandbox not enabled. The following executables must include the "com.apple.security.app-sandbox" entitlement with a Boolean value of true in the entitlements property list: [( "app.rango.Rango.pkg/Payload/Rango for Safari.app/Contents/MacOS/Rango for Safari" )] Refer to App Sandbox page at https://developer.apple.com/documentation/security/app_sandbox for more information on sandboxing your app.
I don't know why this is happening. I have app sandbox enabled in both the app and the extension target. I have both entitlement files. When executing codesign -d --entitlements :- /path/to/binary I get the following:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>com.apple.security.app-sandbox</key><true/><key>com.apple.security.files.user-selected.read-only</key><true/><key>com.apple.security.get-task-allow</key><true/><key>com.apple.security.network.client</key><true/></dict></plist>
If I check on Activity Monitor, on the sandbox column it shows true. I have no idea why I keep getting this error when all indicates that the app is actually sandboxed.
I am currently developing a Chrome, Firefox and Safari web extension, and I am facing a CSP issue on the content script on Safari.
The extension I develop has a content script that injects an img tag in the DOM of web pages the user is visiting. That img tag fetches its content at a specific URL.
On Chrome and on Firefox, the img tag content fetches the content at the URL with no issue on every web pages, including those that set the CSP header img-src.
On Safari, I'm getting the following error on web sites that set the img-src CSP header:
Refused to load https://axxlfrmnpq.cloudimg.io/www.macifavantages.fr/wp-content/uploads/2021/06/Garmin-logo.png?func=bound&w=225&h=113 because it does not appear in the img-src directive of the Content Security Policy.
Here is the actual CSP img-src header content of the web page where, on Safari, the injected img tag does not load the content at https://axxlfrmnpq.cloudimg.io/www.macifavantages.fr/wp-content/uploads/2021/06/Garmin-logo.png?func=bound&w=225&h=113:
Content-Security-Policy: img-src https://secure.adnxs.com https://www.facebook.com https://.garmin.cn 'self' data: .garmin.com .trustarc.com .truste.com https://static.garmincdn.com https://www.google.com https://www.google.co.uk https://prefmgr-cookie.truste-svc.net https://res.cloudinary.com https://res.garmin.com https://.criteo.com https://.doubleclick.net https://www.googleadservices.com https://px.adentifi.com https://rtb.adentifi.com https://.teads.tv https://www.googletagmanager.com https://bat.bing.com https://.yahoo.com https://sync.outbrain.com https://*.google-analytics.com https://stats.g.doubleclick.net https://static.hotjar.com https://script.hotjar.com .akamaihd.net https://.tealiumiq.com https://deploytealium.com https://pixel.mediaiqdigital.com;
My question is, is the page CSP blocking the img tag injected in the web page by the extension's content script?
If so, is this behavior documented somewhere, or is it a Safari bug?
I saw there is a similar post on the forum, but I couldn't find if the issue is a bug or if it's the expected behavior on Safari: https://developer.apple.com/forums/thread/651542?login=true.
Thank you very much for your help.
There does not appear to be any way to use or create iCloud passkeys with a Safari Web Extension, either using the navigator.credentials API in an extension origin webpage such as the popover, or using the AuthenticationServices framework in the SafariWebExtensionHandler.
I've setup an associated domain for my plugin, and I know it works for the host application. But I get errors trying to do so in the web extension target.
createCredentialRegistrationRequests results in the following error:
Domain=com.apple.AuthenticationServices.AuthorizationError Code=1004 "Application with identifier <ID> is not associated with domain <RPID>
The other problem, assuming the entitlement works correctly for the web extension, is that there is no NSWindow to use as the presentation target from the SafariWebExtensionHandler.
Trying to use the navigator.credentials.create JS API (which is the preferred method, frankly, in a web extension) results in the following error:
NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
Chrome has a great solution for this that I believe should be adopted by Safari. If an extension has host permissions for a relying party it wants to claim, or if it has an associated domain entitlement for it, webauthn operations should be allowed.
As of IOS 18.3, there browser.tabs.create methods active property which is supposed to determine whether a tab get open in the active window or not is not working as it should. I have the active property set to false but the tab still gets opened and is active on the window. Tested on older ios versions 18.2 and below and it works as it should.
please advise
hi, I'm having an issue with Safari devlop menu "Web Extension Background Content" menu item being grayed out. I cant do any debugging right now and its becoming mission critical for us. Any help is appreciated.
Thank you,
Sometimes the Safari App Extension i'm developing does not show up in my Safari Extensions unless i change mu bundle identifier to some unique name.
Even if I delete all other apps i've built with the same (and different) bundle ID, the extension is still does not show up.
The only solution for me is to always change the bundle ID.
For example:
Now it is "kopyl.tab-finder-10"
If i change it to "kopyl.tab-finder-11", the extension does show up in the Safari extensions settings page again.
Is there any other way to fix it?
I want use the Safari Extension to decorate the window.fetch function, But No matter how I try, I can't get the fetch function to execute correctly. I was going through the documentation: https://developer.apple.com/documentation/safariservices/using-injected-style-sheets-and-scripts
and found this sentence:
"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 that you include in the webpage run in isolated worlds, with no access to each other’s functions or data."
Does this mean I can't modify the window object in the content script just like a Chrome extension does with the webpage?
BTW, In chrome I use chrome.scripting.executeScript API, and in
plasmo I just use world: "MAIN" content script's config to achieved this feature.
We have a Web Extension that uses firebase for auth. It was working fine until the latest version of Safari 18.3 got released few days ago on January 27, 2025.
All of out extension versions stopped working on it; even the ones that are published on App Store. It uses FirebaseJS v9.23.0.
Same version of the extension are working fine on other browsers. We use onAuthStateChanged to listen to auth related events; but it is never fired now.
Hello,
I am developing Safari Content Blocker extension and discovered that it frequently fails to load with large amount of rules. Currently I have over 45k and most of the time when I reload the extension on iOS 18 (iPhone 12) it ends with error:
Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.SafariServices.ContentBlockerLoader" UserInfo={NSDebugDescription=connection to service named com.apple.SafariServices.ContentBlockerLoader} #0
And the simpler message is just:
Couldn’t communicate with a helper application.
From what I managed to find (for example here - https://developer.apple.com/forums/thread/756931) the limit for blocking rules should be 150k items.
It was previously 50k but got increased years ago.
Is there anything special I need to do to get the extension to work reliably with say 100k items?
I am usng the JSON format from the docs:
{
"trigger": {
...
},
"action": {
...
}
},
{
"trigger": {
...
},
"action": {
...
}
}
]
My trigger is url-filter and the action is type: block
I was thinking about providing multiple JSON files in attachments property of NSExtensionItem but apparently that is not supported.
Thanks for help!
I am using SFSafariViewController to process payments via a Stripe checkout URL. Once the payment is completed, the user is redirected to a success URL. I have also added associated domains for deep linking. Below is my implementation:
func presentCheckout(url: String) {
showProgressHUD()
let checkoutURL = URL(string: url)!
safariVC = SFSafariViewController(url: checkoutURL)
safariVC.delegate = self
self.present(safariVC, animated: true)
}
// Delegate method implementations
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
print("SafariViewController dismissed")
// Handle dismissal
}
func safariViewController(_ controller: SFSafariViewController, initialLoadDidRedirectTo URL: URL) {
print(URL.absoluteString)
if URL.absoluteString.contains("xsworld/payment/stripe/checkout/success") {
controller.dismiss(animated: true) {
if URL.absoluteString.contains("/v1/resources/xsworld/payment/stripe/checkout") {
NotificationCenter.default.post(
name: Notification.Name("StripePaymentStatus"),
object: nil,
userInfo: ["url": URL]
)
}
}
} else if URL.absoluteString.contains("xsworld/payment/stripe/checkout/cancel") {
// Handle failure
NotificationCenter.default.post(
name: Notification.Name("StripePaymentStatus"),
object: nil,
userInfo: ["url": URL]
)
}
}
func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
if didLoadSuccessfully {
print("Initial page loaded successfully")
} else {
print("Initial page load failed")
}
}
Issue:
The safariViewController(_:initialLoadDidRedirectTo:) method does not always get called after the payment is completed. Sometimes it works as expected, and sometimes it does not trigger at all.
What I’ve Tried:
Ensuring the associated domains for deep linking are correctly set up.
Checking the success and failure URLs.
Debugging to see if the redirect happens but is not detected.
What I Need Help With:
I want to ensure that the redirection always works after the payment process is completed, whether through deep linking or another reliable approach. How can I guarantee that my app correctly detects and handles the redirect every time?
Any guidance or best practices would be greatly appreciated.
I have an extension which was working fine on older Safari version, but it is getting killed after I upgraded the browser to Safari 18 and higher.
From the system logs I could see, Safari is sending the KILL signal to my browser
2024-11-12 13:51:01.536167-0600 0x95b672 Default 0x0 1 0 launchd: [pid/45238/SafariExt [45463]:] signal service: caller = Safari[45238], value = 0x9
2024-11-12 13:51:01.536453-0600 0xfab Default 0x0 382 7 WindowServer: (SkyLight) [com.apple.SkyLight:default] [ ConnectionDebug ] Closing conn 0xf955b, PID 45463 in session 257 on console2024-11-12 13:51:01.536474-0600 0x95b674 Default 0x0 1 0 launchd: [gui/503 [100018]:] service inactive: com.apple.xpc.launchd.unmanaged.SafariExtension.45463
2024-11-12 13:51:01.536479-0600 0x95b674 Default 0x0 1 0 launchd: [gui/503 [100018]:] removing inactive unmanaged service: com.apple.xpc.launchd.unmanaged.SafariExtension.454632024-11-12 13:51:01.537354-0600 0x95b907 Default 0x0 354 0 launchservicesd: [com.apple.processmanager:front-35286506] QUITTING: pid=45463 asn=0x-0x176176 foreground=0 wasFront=0
2024-11-12 13:51:01.537375-0600 0x95b672 Default 0x0 1 0 launchd: [pid/45238/SafariExt [45463]:] exited due to SIGKILL | sent by launchd[1], ran for 342ms
2024-11-12 13:51:01.537380-0600 0x95b672 Default 0x0 1 0 launchd: [pid/45238/SafariExt [45463]:] service state: exited
2024-11-12 13:51:01.537384-0600 0x95b672 Default 0x0 1 0 launchd: [pid/45238/SafariExt [45463]:] internal event: EXITED, code = 0
2024-11-12 13:51:01.537385-0600 0x95b672 Default 0x0 1 0 launchd: [pid/45238/SafariExt [45463]:] job state = exited
Just before this, I see a macOS error
2024-11-12 13:51:06.789342-0600 0x95b74f Default 0x0 45238 0 Safari: (Security) [com.apple.securityd:security_exception] MacOS error: -67054
This occurs only in my customer machines but not in my test machines. I have verified the code signing, certificate validity & entitlements are fine.
Hello All,
On our iOS app, we plan to show tutorial (WKWebview) only in case user has safari extension disabled.
How can iOS app know about status of Safari extension.
Thanks,
Anup
I’m currently porting a Chrome Extension to Safari and integrating it with native messaging in a Safari Web Extension. As part of this, I’m building a proxy to forward messages between the web extension and a socket in another application, both ways. Additionally, the socket occasionally broadcasts messages that also need to be sent to the web extension.
The issue I’m facing is that the app extension terminates whenever I call context.completeRequest(returningItems: nil), which prevents me from listening for incoming messages from the socket (I'm using the Network Framework). To work around this, I’ve tried not calling context.completeRequest(returningItems: nil), which keeps the app extension running. However, I’m unsure if this is the right approach—currently, I’m simply ignoring the response and relying entirely on SFSafariApplication.dispatchMessage.
According to the documentation, the app extension lifecycle ends when the system terminates it, but I need to keep the socket listener active.
Has anyone encountered a similar issue, or does anyone have suggestions for maintaining the socket connection while adhering to the app extension lifecycle?
Any insights would be greatly appreciated!
Is there a way to read all URLs of the currently open Safari TabGroup from a Safari Extension? In macOS and iOS
Hello! I've made a Safari extension that supports command "ReTab", and a couple of month ago, adding a customized macOS shortcut for Safari with menu title "ReTab" did trigger the extension. However, it's not working anymore and I'm not sure if it's from macOS/Safari update or because I changed manifest from v2 to v3 - could you help check if there's anything wrong with either the manifest.json or background.js? (the default Cmd+E still works)
Thank you in advance!
Xun
manifest.json:
{
"manifest_version": 3,
"default_locale": "en",
"name": "ReTab",
"description": "Go to the last active tab with Cmd+E!",
"version": "1.4",
"homepage_url": "https://LycheeIsle.com",
"background": {
"service_worker": "background.js"
},
"action": {
"default_icon": "images/toolbar-icon.svg"
},
"permissions": [ "commands", "tabs", "storage" ],
"commands": {
"ReTab": {
"suggested_key": {
"default": "Command+E"
},
"description": "Go to the last active tab"
}
},
"options_page": "options.html"
}
in background.js, I have this line which should listen to the command, and Cmd+E works but any customized shortcut for "ReTab" in Safari doesn't:
browser.commands.onCommand.addListener(async (command) => {
if (command === "ReTab" || command === "retab") {
await retab()
}
});
I've been developing a Safari web extension for MacOS and iOS, and I'm running into a very strange issue.
I ported over my Chrome extension to Safari, and for several days as I was iterating on the extension (change code, build, run, test in Safari), everything worked perfectly fine.
Once I was finished with the extension, I followed the instructions on how to prepare to submit the Safari web extension (and it's containing MacOS and iOS apps) to the App Store for review.
For the MacOS app and Safari web extension on Mac, I changed my target from "My Mac" (which I'd been using for testing), to "Any Mac". I then went to the "Product" menu in Xcode and selected "Archive"
That's when things started to go wrong.
The next time I went to Safari, my web extension could no longer find critical files to run the extension (such as background.js, popup.html, etc.) This was despite there being no code changes before or after me creating a build archive.
When I restarted Safari, the extension no longer appeared in the list of extensions within preferences. No matter what I do (clean build folder and re-run, restart Safari, restart Xcode, restart computer), nothing will get my extension to show up in Safari again.
Note that this does not happen with the Safari web extension in the iOS simulator. It only happens on Mac.
I was confident that my extension was working, so I submitted my extension to the Mac App Store for review. It was approved, and a few users have downloaded it and it works totally fine.
To further try to figure out what's going on, I created a new sample Xcode project. From the new project screen, I chose the "Safari web extension" under "Multiplatform".
Without making any code changes, I build and run that project, and the default MacOS app and Safari web extension from the template. I then immediately create an archive (with no code changes). Once I try to run the project for my Mac again, the extension no longer works.
So I have verified that this problem does not have to do with my extension's code, but I cannot for the life of me figure out what is wrong. I have examined every possible build setting, but given that I ran a default project template, made no changes, and it still had this problem, I'm not sure what else could be wrong.