Search code examples
mobile-safaribrowser-extensionsafari-web-extension

Safari Web Extension background script becomes unresponsive after 30 seconds


Overview

I'm experiencing a Safari Web Extension issue where the non-persistent background script seems to crash after 30 seconds even when the content script is messaging it.

Here is a minimal-reproducible example. When running in an emulator, the background script will stay responsive forever. However, when running on a physical device, the background script becomes non-responsive after 30 seconds of activity. It never becomes responsive again until I toggle the extensions enable/disable toggle, after which it stays active for 30 seconds and then crashes again.

Steps to Reproduce

  1. Clone this repo
  2. Open in Xcode and run targeting a physical device
  3. Open Safari on the device and enable the extension
  4. Open a new tab and navigate to https://www.google.com
  5. From your Mac, open the Safari Web Inspector and navigate to the extension's background page
  6. You will see messages being sent from the content script to the background script every 1 second
  7. After 30 seconds, the background script will stop receiving messages. Trying to use the console to interact with the background script, e.g., typing console.log("hello") will show that it is no longer responsive.

Additional Findings

If you look through the content script code you'll see that I am calling runtime.sendMessage every 1 second which always causes the background script to crash after 30 seconds.

I started to play with the 1 second interval to see if it behaved differently. Increasing it to 2 seconds caused a crash after 15 calls (also 30 seconds). Increasing the interval to 3 seconds caused a crash after 10 calls (also 30 seconds).

Increasing to 4 seconds causes the background script to behave how I'd expect... that is it never crashes and is able to respond to the sendMessage request forever.


Solution

  • This issue appears to be fixed in iOS 17.6 Beta, according to Apple's Safari release notes: https://developer.apple.com/documentation/safari-release-notes/safari-17_6-release-notes