Safari Extensions

RSS for tag

Enhance and customize the web browsing experience on Mac, iPhone, and iPad with Safari Extensions

Posts under Safari Extensions tag

122 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Safari Extension state using declarative device management
So recently Intune add support for controlling safari web extension enablement using the new ddm configuration added in Macos 15, but unfortunately I can't make it work no matter what I try. On the destination machine I see the that a user declaration for safari extension has been created, but there is not details on which extension they applied and it seems faulty (See attachment) I have 2 questions: Has anyone managed to make it work? Is there a way to test this declaration like I can do with Mobile config by manually load it to the machine? Thank you.
1
0
369
Sep ’24
Safari Extension Stops on iOS 17.5.1 - 18
We are encountering an issue where the Safari extension we are developing stops working while in use on relatively new iOS versions (confirmed on 17.5.1, 17.6.1, and 18). Upon checking the Safari console, the content script is displayed in the extension script, so the background script or Service Worker must be stopping. The time until it stops is about 1 minute on 17.5.1 and about one day on 17.6.1 or 18. When it stops, we would like to find a way to restart the Service Worker from the extension side, but we have not found a method to do so yet. To restart the extension, the user needs to turn off the corresponding extension in the iPhone settings and then turn it back on. As mentioned in the following thread, it is written that the above bug was fixed in 17.6, but we recognize that it has not been fixed. https://forums.developer.apple.com/forums/thread/758346 On 17.5.1, adding the following process to the background script prevents it from stopping for about the same time as on 17.6 and above. // Will be passed into runtime.onConnect for processes that are listening for the connection event const INTERNAL_STAYALIVE_PORT = "port.connect"; // Try wake up every 9S const INTERVAL_WAKE_UP = 9000; // Alive port var alivePort = null; // Call the function at SW(service worker) start StayAlive(); async function StayAlive() { var wakeup = setInterval(() => { if (alivePort == null) { alivePort = browser.runtime.connect({ name: INTERNAL_STAYALIVE_PORT }); alivePort.onDisconnect.addListener((p) => { alivePort = null; }); } if (alivePort) { alivePort.postMessage({ content: "ping" }); } }, INTERVAL_WAKE_UP); } Additionally, we considered methods to revive the Service Worker when it stops, which are listed below. None of the methods listed below resolved the issue. ① Implemented a process to create a connection again if the return value of sendMessage is null. The determination of whether the Service Worker has stopped is made by sending a message from the content script to the background script and checking whether the message return value is null as follows. sendMessageToBackground.js let infoFromBackground = await browser.runtime.sendMessage(sendParam); if (!infoFromBackground) { // If infoFromBackground is null, Service Worker should have stopped. browser.runtime.connect({name: 'reconnect'}); // ← reconnection process // Sending message again infoFromBackground = await browser.runtime.sendMessage(sendParam); } return infoFromBackground.message; Background script browser.runtime.onConnect.addListener((port) => { if (port.name !== 'reconnect') return; port.onMessage.addListener(async (request, sender, sendResponse) => { sendResponse({ response: "response form background", message: "reconnect.", }); }); ② Verified whether the service worker could be restarted by regenerating Background.js and content.js. sendMessageToBackground.js export async function sendMessageToBackground(sendParam) { let infoFromBackground = await browser.runtime.sendMessage(sendParam); if (!infoFromBackground) { executeContentScript(); // ← executeScript infoFromBackground = await browser.runtime.sendMessage(sendParam); } return infoFromBackground.message; } async function executeContentScript() { browser.webNavigation.onDOMContentLoaded.addListener((details) => { browser.scripting.executeScript({ target: { tabId: details.tabId }, files: ["./content.js"] }); }); } However, browser.webNavigation.onDOMContentLoaded.addListener was not executed due to the following error. @webkit-masked-url://hidden/:2:58295 @webkit-masked-url://hidden/:2:58539 @webkit-masked-url://hidden/:2:58539 ③ Verify that ServiceWorker restarts by updating ContentScripts async function updateContentScripts() { try { const scripts = await browser.scripting.getRegisteredContentScripts(); const scriptIds = scripts.map(script => script.id); await browser.scripting.updateContentScripts(scriptIds);//update content } catch (e) { await errorLogger(e.stack); } } However, scripting.getRegisteredContentScripts was not executed due to the same error as in 2. @webkit-masked-url://hidden/:2:58359 @webkit-masked-url://hidden/:2:58456 @webkit-masked-url://hidden/:2:58456 @webkit-masked-url://hidden/:2:58549 @webkit-masked-url://hidden/:2:58549 These are the methods we have considered. If anyone knows a solution, please let us know.
1
1
340
3w
declarativeNetRequest.getMatchedRules() not working on iOS 18 Safari
declarativeNetRequest.getMatchedRules() gives us the below error: Error retrieving tabs or matched rules: – Error: Invalid call to declarativeNetRequest.getMatchedRules(). The 'activeTab' permission has not been granted by the user for the tab. We have added the "activeTab" permissions in the manifest (version 2). And in the device Safari extension settings we see that user has given permission as "allow".
2
0
304
Sep ’24
WebAssembly wasm not able to load on Safari Web Extension
Hi, I am having issue with WebAssembly not able to load wasm file on Safari web extension. It is showing CompileError: Refused to create a WebAssembly object because 'unsafe-eval' or 'wasm-unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval'". It was working fine 2 month ago, my original CPS is "script-src 'self' 'unsafe-eval'". But now it is not accepting 'unsafe-eval', I also tried 'wasm-unsafe-eval' did not work. Is there any changes on Safari browser regarding the CSP for WebAssenbly? Please let me know what CPS value will work. Here is the example code on how I load the WebAssembly wasm file. fetch('test_wasm_lib.wasm') .then(response => { if (!response.ok) throw new Error('Network response was not ok'); return response.arrayBuffer(); }) .then(bytes => WebAssembly.instantiate(bytes)) .then(results => { // Use your WebAssembly instance here console.log('load wasm success') }) .catch(error => { console.error('Error loading WASM:', error); });
0
2
375
Sep ’24
Safari 18: fetch() in safari extension does not include credentials
It seems Safari 18's fetch() does not include credentials even credentials: include and safari extension has host_permissions for that domain. Is there anyone has this problem? I try to request in popup.js like this: const response = await fetch( url, { method: 'GET', mode: 'cors', credentials: 'include', referrerPolicy: 'no-referrer', } ); and it does not include the cookie from host_permissions. Those code worked in Safari 17 (macOS Sonoma).
3
2
472
Sep ’24
Safari extension - badgeText and title set for a tab
I am building Safari extension. In my background script I am setting badge text and title like this: browser.action.setBadgeText({text: badgeText, tabId: tabId}); browser.action.setTitle({title: badgeText + " found images", tabId: tabId}) , where tabId is correct id of current tab. I was expecting that in this way I am setting a different badge and title for different tabs, so that badge and title would automatically switch if I activate different tab. However this does not happen, badge and title behave as if set globaly and don't change with tabs. How is this expected to work? I have also tried to set badge globally, and update it every time user switches a tab. I have set up listener like this: browser.tabs.onActivated.addListener(function(actInfo) { console.log("switched tab to " + actInfo.tabId); }); , however the event never fires, tab switch is never logged in console. Am I doing something wrong here? This is my manifest, if there was a problem with permissions or something similar. { "manifest_version": 3, "default_locale": "en", "name": "Test", "description": "Test Extension", "version": "1.0", "icons": { "48": "images/icon-48.png", "96": "images/icon-96.png", "128": "images/icon-128.png", "256": "images/icon-256.png", "512": "images/icon-512.png" }, "action": { "default_title": "a test title", "default_popup": "popup/hello.html", "default_icon": { "16": "images/toolbar-icon-16.png", "19": "images/toolbar-icon-19.png", "32": "images/toolbar-icon-32.png", "38": "images/toolbar-icon-38.png", "48": "images/toolbar-icon-48.png", "72": "images/toolbar-icon-72.png" } }, "web_accessible_resources": [ { "matches": ["*://*/*"], "resources": ["images/*", "css/*", "scripts/lib/*"] } ], "background": { "service_worker": "scripts/background.js", "type": "module" }, "content_scripts": [ { "js": [ "scripts/content.js" ], "matches": [ "http://*/*", "https://*/*" ], "css": ["css/style.css"], "run_at": "document_end" } ], "permissions": [ "nativeMessaging", "tabs" ] }
3
0
283
Oct ’24
Enable/disable Safari web extension content blocker using declarative_net_request in manifest
Is it possible to enable/disable the enabled flag before the extension is loaded? we want to have a button in our app which controls the availability of the content blocker ruleSet in declarative_net_request in manifest (version 2). "declarative_net_request": { "rule_resources": [ { "id": "ruleset_1", "enabled": true, "path": "ruleset_1.json" } ] },
3
0
344
Sep ’24
Content blocker extensions vs content blocking using Safari extensions for dynamic URLs
We have observed that blocking content using Safari web extension does not fetch few URLS within the #document (documentURLs) because the onBeforeRequest webextension API is currently not available in Safari iOS. But it works fine using the Content blocking extension. We have a list of URLs which we want to block from the website. Which extension would you suggest the Content blocking extension or the Safari web extension?
1
0
260
Sep ’24
@@extension_id replacement in CSS file fails in Sequoia, Safari 18
Typically, you can use the @@extension_id special string to reference the absolute path into the bundled resources of an extension, such as an image or a custom font, in a CSS file. However, this broke with Safari 18. Consider this section in a popup.css file: .card-icon { height: 16px; width: 20px; background-image: url(safari-web-extension://__MSG_@@extension_id__/images/card.svg); background-size: 20px 16px; } In Safari 17.4, once loaded in the browser, @@extension_id is replaced with E8BEA491-9B80-45DB-8B20-3E586473BD47, and the background-image reads as so: background-image: url(safari-web-extension://E8BEA491-9B80-45DB-8B20-3E586473BD47/images/card.svg); But as of Safari 18, the @@extension_id just collapses to an empty string, and the background-image reads as so: background-image: url(safari-web-extension:///images/card.svg); and the svg fails to load with the following error: "Failed to load resource: You do not have permission to access the requested resource." This is a regression, does to match the behavior of the other major browsers, and should be fixed. Filed with Feedback ID: FB15104807
2
1
492
Sep ’24
Safari DNR Redirect Issue When Using Address Bar for Default Search Engine Queries
I’ve noticed that redirecting from one web page to another using DNR (Declarative Net Request) no longer works if: The source page is a search results page of the default search engine, and The user searches for a keyword from Safari’s address bar. Has this functionality been degraded, or is it an intentional restriction? I'd like a response from Apple. Steps to Reproduce Create a Safari extension that adds the following rule using browser.declarativeNetRequest.updateSessionRules() in background.js: { id: 37457985, priority: 1, action: { type: "redirect", redirect: { regexSubstitution: "https://search.brave.com/search?q=\\1" }, }, condition: { regexFilter: "https://duckduckgo.com/\\?(?:.*&)?q=([^&]*).*", resourceTypes: ["main_frame"] } } Enable the extension in Safari. Set Safari’s default search engine to DuckDuckGo. Type "hello" in the address bar to search for it. Expected: Search results for "hello" appear in Brave Search. Actual: Safari navigates to neither DuckDuckGo nor Brave Search. For further reference, please see: Sample Xcode project: GitHub link Demo video: GitHub link Environment I’ve confirmed this issue on the following environments: Safari Technology Preview 202 (macOS Sonoma 14.6.1 (23G93)) iOS 18 RC (22A3354) This issue does not occur in the latest release version of Safari 17.6 (19618.3.11.11.5) on macOS, so I believe it started with the current development version of Safari. Context My Safari extension, Redirect Web for Safari, uses DNR to redirect one web page to another. While the extension is not specifically designed to change the default search engine, some users use it to set their preferred search engine. Unfortunately, this issue will break their use case. Additional Information This issue only occurs when searching from the address bar. It does not happen when searching directly from https://duckduckgo.com. I haven’t submitted this issue via Feedback Assistant because I’m unsure if it’s a bug or intentional behavior. I’d like to confirm if this is by design first.
2
0
488
Sep ’24
Port messages ignored in content scripts in macOS Sequoia
Messages intended for a port connection created in content scripts are unable to receive messages from the extension background script. Consider a content.js and background.js with the following contents: content.js: const port = chrome.runtime.connect({ name: 'TEST' }) // THIS IS NEVER RECEIVED port.onMessage.addListener((message) => { console.log('RECEIVED TEST MESSAGE', message) }) background.js: chrome.runtime.onConnect.addListener((port) => { if (port.name !== 'TEST') return console.log('test port connected', port) console.log('SENDING PORT MESSAGE') port.postMessage('HELLO') }) This behavior was broken in Sequoia, Safari 18. This behavior also does not match that of Firefox and Chrome, which are able to receive port messages in content scripts. It's also worth noting that UI documents with the same origin as the extension, such as a popup or iFrame, ARE able to use the port messaging as expected. However, this bug is a huge regression and should really be addressed. I've already filed an issue via Apple Feedback with the ID of FB14721836, over a month ago, but never received a response. I'm posting here for more visibility and hope a fix can be included before Sequoia goes live next week.
3
0
456
Sep ’24
Safari Web Extensions: Unexpected tab ID change when redirecting to extesnion URL in a tab
Hello! We have been testing the upcoming Safari 18 on macOS 15 Sequoia betas and noticed one inconsistent detail about Safari Web Extensions support compared to other browser which implement Web Extensions (Chrome, Edge, Firefox). Background We have a Safari Web extension which is monitoring navigation events using browser.tabs.onUpdated API. navigation event subscription code sample browser.tabs.onUpdated.addListener((tabId, changeInfo, details) => { onTabUpdated(tabId, changeInfo, details) }); navigation event handling code sample onTabUpdated(tabId, changeInfo, details) { console.log(`onTabUpdated: ${tabId}`, changeInfo, details); // check URL in the tab for safety } }); If the extension detects that the user navigates to an unsafe URL, it redirects the user to a page hosted by the extension. It's an HTML resource from the extension bundle. The extension is using browser.tabs.update API to redirect a specific tab to an internal page. const internalPage = browser.runtime.getURL("popup.html"); browser.tabs.update(tabId, { url: internalPage }); Discovered problem When we use browser.tabs.update API browser.tabs.update(tabId, { url: internalPage }); to redirect the user from an unsafe page, we notice that the redirected tab changes its identifier. We know that is the case because we see another API firing. It's called browser.tabs.onReplaced. We have a similar subscription for those events. When the page is redirected, the onTabReplaced handler is firing and informs us about the tab ID change after the redirect. onTabReplaced(addedTabId, removedTabId) { console.log(`onTabReplaced: ${removedTabId} -> ${addedTabId}`); } This is problematic for us in several ways: The extension keeps track of the tab ID so that when the embedded HTML page is loaded, it can still tell the user about the original URL that was blocked. The behavior observed in Safari 18 breaks current expectations of our code and breaks the functionality of our extension. This behavior is specific to Safari 18. Safari 17 does not behave this way which means that we will need to deploy an update to our Safari extension to mitigate that bug on the upcoming Safari version. Moreover, this behavior is not observed in other browsers which implement Web Extensions standard (Chrome, Edge, Firefox). All these browsers preserve the tab ID after redirect. That is a problem for us as we run the same code in all 4 browsers that we support. This will cause increase of code complexity to cover Safari as an exception out of common rule. Environment Safari version 18.0 (20619.1.26.31.6) and all prior Safari 18 betas. issue does not happen on Safari 17. macOS 15 beta 8 (24A5331b) and all prior macOS 15 betas. issue has been successfully reproduced on macOS 14 with Safari 18 betas which points to the fact that the issue is not exclusive to macOS 15. Safari 18 brings the faulty logic. The issue has been confirmed and reproduced in a sample Xcode prowejt provided by Apple called "Sea Creator". So the issue is not specific to a single extension. Feedback case FB14975378. It contains sample code, the full Xcode project, screenshots and sysdiagnose. Any advice or assistance is highly appreciated!
2
0
583
Sep ’24
iOS Safari Extension Keeps Turning Off?
We have an iOS Safari extension currently distributed via Testflight. I’ve noticed that after an indeterminate period of time (sometimes days, sometimes weeks) our safari extension will stop working. It will need to be turned on again from the system general -> safari -> extensions menu. This is occurring on both iPhones and iPads running 17.6.1. Is there any condition that will cause the system to disable a safari extension, requiring the user to reopen iOS settings to re-enable?
1
0
327
Sep ’24
iOS Safari extensions turning themselves off?
We have an iOS Safari extension currently distributed via Testflight. I’ve noticed that after an indeterminate period of time (sometimes days, sometimes weeks) our safari extension will stop working and will need to be turned on again from the system general -> safari -> extensions menu. This is occurring on both iPhones and iPads running 17.6.1. Is there any condition that will cause the system to disable a safari extension, requiring the user to reopen iOS settings to re-enable?
1
0
253
Sep ’24
Enforce Safari Extension state using device management
Hey, Im trying to utilize the new DDM features introduce in Safari 18 & macOS 15 and enabling extension using my MDM (Intune in my case). For some reason, it doesn't seems to work on my mac machine running macOS 15 beta. Intune support claims that everything is configured as it should on their end, and there is a problem with device or configuration. I used Apple documentation and the configuration YAML in apple device management repo So I don't really sure what I am missing. Has someone managed to make it work using MDM (intune, jamf, etc')? And if so can he shared the configuration? Thanks.
2
0
653
Sep ’24
Issues with Displaying Language Tags Compliant with RFC 5646
Hello, I'm currently facing some issues with localization for the Safari extension on iOS: Issues with Language Tags: Folder names like pt-BR (Brazilian Portuguese) and pt-PT (European Portuguese) placed in the Resources/_locales/ directory are not displaying the respective languages correctly; instead, the default English is shown. Similarly, using folder names like zh-CN (Simplified Chinese) and zh-TW (Traditional Chinese) also results in default English display instead of the intended Chinese language. Conversely, when changing the folder names to pt (Portuguese general) and zh (Chinese general), the languages display correctly. Could you please provide any recommendations or tips regarding language tag settings and how to ensure they are properly recognized according to RFC 5646? Thanks for your help! Best,
5
0
650
Oct ’24
How to reduce manual user interaction in Safari Extension setup?
Currently, after installing our Safari Extension, users must manually enable it within Safari Preferences under Extensions settings. This involves: Navigating to Safari Preferences. Selecting Extensions. Checking the checkbox to enable the Extension. Clicking on “Always Allow on Every Website” to grant necessary permissions. We are seeking guidance or the possibility of introducing an automation feature that would streamline these steps. The goal is to reduce manual user interaction. Are there existing APIs or methods within Safari's framework that we could utilize to automate these setup steps? What are the best practices for ensuring a smooth setup process? Thanks.
0
0
240
Aug ’24
Open specific web extension in safari settings (iOS/App/Swift)
Hi all, I have a problem with trying to use UIApplication.shared.canOpenURL to open a specific web extension in the safari settings. When executing the code below the safari extension menu is shown but not the settings for the specific extension: if let url = URL(string: "App-prefs:SAFARI&path=WEB_EXTENSIONS/NAME_OF_EXTENSION") { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } However, the weird thing is that when executing the above I can see some kind of an event that looks like it tries to click the specific extension. Furthermore, if I keep the settings open and tries to execute the code again it actually works, and the specific web extension's settings is open. Hope someone can help.
0
0
292
Aug ’24