colyseus / colyseus.js

⚔ Colyseus Multiplayer SDK for JavaScript/TypeScript
https://docs.colyseus.io/getting-started/javascript-client/
MIT License
410 stars 107 forks source link

Handle localStorage Access Denied Error in Chrome Due to Third-Party Cookie Blocking #139

Open CookedApps opened 9 months ago

CookedApps commented 9 months ago

Description

After the recent update to Chrome in 2024, which blocks third-party cookies by default, our game, which is hosted in an iframe on a games platform, encounters a critical issue. Chrome's new policy leads to a situation where accessing localStorage throws an error if no user consent is given. Our game uses colyseus.js, which seems to internally access localStorage and thus causes a crash upon page load.

Error Encountered

The specific error message we encounter is:

Uncaught DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.

Possible Source of the Error

This issue seems to originate from the Storage.ts class, particularly in the getStorage function, which attempts to access the localStorage object to check its availability in the current environment.

Suggested Solution

A potential solution to circumvent this issue could be wrapping the window.localStorage access in a try / catch block. This would gracefully handle the exception caused by Chrome's third-party cookie policy and prevent the application from crashing.

Steps to Reproduce

  1. Host a game that uses colyseus.js in an iframe on a third-party platform.
  2. Load the game in the latest version of Chrome with default settings (third-party cookies blocked).
  3. Observe the crash upon page load with the aforementioned error in the console.

or: Try out our particular game at Poki with third party cookie blocking enabled.

I believe this issue is critical for any web-based games or applications using colyseus.js in similar environments and would greatly appreciate a timely resolution. Thank you for your attention to this matter!

endel commented 9 months ago

Thank you for the detailed report @CookedApps!

I've just pushed a new version (0.15.18) using your suggested solution as a workaround.

The Storage class is only used internally to store the authentication token - I think we'll need to switch to IndexedDB or other method for that instead. Let's leave this issue open until we have a proper solution as anybody using the new auth system under these restrictions will be affected.

CookedApps commented 9 months ago

Thank you for the quick fix @endel! Yeah, I was a bit confused because we don't use the auth feature. 😄