Replacing window.localStorage implementation for Facebook Instant Games

244 views Asked by At

I am preparing a game for publishing at Facebook Instant Games.

My game uses Pixi.js and jQuery UI - and saves some user settings like "color theme" and "sound volume" in window.localStorage:

game screenshot

However when trying to access it from my Instant Game, I get the error:

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

I guess the root cause is that Facebook Instant games run in an iframe.

However, I have already published my game at the Yandex Games platform and there they offer a replacement for localStorage by running the following code:

ysdk.getStorage()
    .then(safeStorage => Object.defineProperty(window, 'localStorage', 
        { get: () => safeStorage }))
    .then(() => {
       localStorage.setItem('key', 'safe storage is working');
       console.log(localStorage.getItem('key'))
    });

So I wonder if the same trick is possible by using FBInstant.player.setDataAsync() and FBInstant.player.getDataAsync() found in the Instant Games SDK?

I have tried:

Object.defineProperty(window, 'localStorage', 
    { get: () => { 
    getItem: { FBInstant.player.getDataAsync() }, 
    setItem: { FBInstant.player.setDataAsync() } } }));

but that is of course not working... I am not even sure, how to deal with Facebook's async functions here.

1

There are 1 answers

3
mplungjan On

You would need to keep the syntax

Object.defineProperty(window, 'localStorage', 
{ getItem: key => FBInstant.player.getDataAsync(...) , 
  setItem: (key,str) => FBInstant.player.setDataAsync(...)
})

https://developers.facebook.com/docs/games/instant-games/sdk/fbinstant6.1/