Playwright: Failed to Read the localStorage property from Window: Access is denied for this document

Viewed 2959

I have this script to modify localStorage of my browser instance (assuming all definitions are correct). it returns this Error. I have a feeling that this is because Playwright is launching a browser in incognito mode. Is there a way for me to launch browser in normal mode?

Script:

const rdlocalStorage = fs.readFileSync('localstorage.json','utf8');
    const deserializedStorage = JSON.parse(rdlocalStorage);
    console.log (deserializedStorage);
    await page.evaluate((deserializedStorage)=>{
        for (const key in deserializedStorage){
            localStorage.setItem(key,deserializedStorage[key]);
        }
    }, deserializedStorage);

Error Message enter image description here

1 Answers

I don't know why your error happens, but maybe I do have an alternative. Playwright has an API to restore cookies and local storage for you, without you having to code it.

context.storageState is the method which allows you to capture the cookies, local storage, etc. You can either await and use the return value as object, or (await and) save the storage state to a file.

Restoring the storage state is done when creating a new browser context, by means of the storageState property on the options parameter of the browser.newContext method. You can either pass it a storageState object or a path to a storage state file.

These same objects and files can also be used in the @playwright/test runner.

The only thing which is not stored in storage state is the session storage (the 'brother' of the local storage). According to the Playwright docs it's not used so often for authentication state, so they don't have a 'native' method for saving and restoring it. But they do describe how to deal with session storage in case it's needed.

Related