serversideup / webext-bridge

💬 Messaging in Web Extensions made easy. Batteries included.
https://serversideup.net/open-source/webext-bridge
MIT License
547 stars 50 forks source link

Fix back/forward caching issues on Safari #43

Closed Benjadahl closed 1 year ago

Benjadahl commented 2 years ago

Turns out issue #42 was cause by the use of BF cahing in Safari: https://web.dev/bfcache/

BF caching takes the entire JS heap into a cache and reloads this instantly when using the back/forward buttons. The page state is restored from memory instead of being reloaded. This means that our connections would be disconnected when you navigate to a new page, and navigate back again. Example:

  1. Tab has loaded site1.com (A content script is injected with sendMessage calls - which establishes sockets)
  2. Tab load site2.com
  3. Users presses back button to got back to site1.com, so the browser simply puts the old state of site1.com back into memory instead of reloading it. This means that our old sockets wont be intialized, but they have now been disconnected.

Thus the solution is to reconnect them, when the onpageshow event is called, if the persisted field is true.

@zikaari should this event be wrapped in a check for if window is defined in the context? I don't seem to be getting any runtime errors now, but maybe you know of any cases where it would be necessary?

zikaari commented 2 years ago

What do you think of returning the connect from createPersistentPort as an alias like forceReconnect etc. and have content-script.ts do the check and trigger the re-connect if necessary? Just thinking if we can keep the concerns isolated to where they truly belong

Benjadahl commented 2 years ago

What do you think of returning the connect from createPersistentPort as an alias like forceReconnect etc. and have content-script.ts do the check and trigger the re-connect if necessary? Just thinking if we can keep the concerns isolated to where they truly belong

That would definitely make sense. I can probably take a look at it later this week. :)