safarisafari-extension

How to persistent background page in Safari extension


I used xcrun safari-web-extension-converter to convert my chrome extension to safari extension but it built with this warning

Warning: Persistent background pages are not supported on iOS and iPadOS. You will need to make changes to support a non-persistent background page.

Also when using it on safari, it is showing these errors:

Extension errors in safari

How can I debug the errors in the extension? I'm not sure about the error but the persistent page warning seems to be a good place to start with. While searching for it in google, all I got is results for non-persistent background pages.

Do let me know if any more information is required.

PS: The extension option in the "develop" menu of safari is also disabled due to service_worker failed to load error.


Solution

  • From WWDC21-10104:

    The background page is a web page that the browser loads to run your extension's background script. And this page allows your extension to handle events sent by the browser or other parts of your extension. But keeping this page loaded has a performance cost. It can use memory and power as if you were keeping one more tab open and running for every enabled extension. Keeping all these pages loaded all the time can be pretty wasteful. But you can make a background page non-persistent, which means the browser will only load it when your extension actually needs to do work, and the browser can later unload that page when it's been idle for some time. That way, the performance cost is only paid while your extension is doing something useful. This is important because background pages must be non-persistent on iOS, where system memory and battery life are especially at a premium. The web extension templates in Xcode already come with a non-persistent background page, so they're ready to run on iOS. But if you have an existing extension that uses a persistent background page like Sea Creator did, you'll need to change it to be non-persistent. And you can do that by adding that "persistent:" False key in the background section of your manifest.

    So you can solve it by adding this to your manifest.json:

    "background": {
        "scripts": [ "background.js" ]
        "persistent": false
    }