puppeteer: Cannot access localStorage. Access is denied for this document.

Steps to reproduce

Tell us about your environment:

  • Puppeteer version: ^0.13.0
  • Platform / OS version: Windows 10

What steps will reproduce the problem?

Please include code that reproduces the issue.

await(page.evaluate(() => { localStorage.clear(); debug('localstorage cleared'); }));

What is the expected result? Localstorage should be cleared.

What happens instead? exception::Error: Evaluation failed: DOMException: Failed to read the ‘localStorage’ property from ‘Window’: Access is denied for this document.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 5
  • Comments: 16 (6 by maintainers)

Most upvoted comments

Hi @ebidel it seems to work:) like this

       // store in localstorage the token
      await page.evaluateOnNewDocument (
        token => {
          localStorage.clear();
          localStorage.setItem('token', token);
        }, 'eyJh...9_8cw');
      // open the url
      await page.goto('http://localhost:3000/Admin', { waitUntil: 'load' });

Does evaluateOnNewDocument work for this use case? The code you pass it will get injected into the page before other scripts run.

https://pptr.dev/#?product=Puppeteer&version=v1.8.0&show=api-pageevaluateonnewdocumentpagefunction-args

@scottc-netflix I had to do 2 calls to page.goto to be able to use it in my page, first so the url is set for the localStorage and second to load the page with localStorage data

      // open the url
      await page.goto('http://localhost:3000/Admin', { waitUntil: 'load' });
      // store in localstorage the token
      await page.evaluate(
        token => {
          localStorage.clear();
          localStorage.setItem('token', token);
        }, 'eyJh...9_8cw');
      // load the page again so it takes stored data
      await page.goto('http://localhost:3000/Admin', { waitUntil: 'load' });

It would be useful to have means to set all similar data on the browser before loading the page (or as a setup to the current;y loaded page?

// e.g.
await page.goto('some/url', {waitUntil: 'load', localStorage:{token:'abc'}});

@justindujardin localStorage is bound to the page origin. If you require localStorage before page.goto(), you try to get localStorage for about:blank URL, and this is forbidden. You can check this in the browser console:

ab

In case anyone else needs this, evaluateOnNewDocument isn’t available anymore apparently but I was able to achieve the same with https://playwright.dev/docs/api/class-page#page-add-init-script

Example:

await page.addInitScript(() => {
  window.localStorage.setItem(`key`, `"value"`);
});

Note that I had to put some double quotes around the value otherwise the lib I was using to read from localstorage wasn’t working but you may not need those.

Sometimes the pages index will be changed, so get localStorge or the sessionStorage could get the error for: ### Cannot access sessionStorage. Access is denied for this document.

I encountered the same related problem, finally I found the reason. Every time when you launch the browser, I create a new page instead of using the default page that created by the browser. Please try the snippets blow:

beforeAll(async () => {
    browser = await puppeteer.launch()
    // page = await browser.newPage()
    const pages = await browser.pages();
    const page = pages[0];
});

@vsemozhetbyt Yeah, I’m not having a problem, just had information you guys were asking for. 👍

@vsemozhetbyt your test case is so close. The trick is to do the page.evaluate before the page.goto. Imagine you’re setting custom values in localStorage before the page loads (because your app does something with it on page load)

'use strict';

const puppeteer = require('puppeteer');

(async function main() {
    try {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();

        await page.evaluate(() => { localStorage.clear(); });

        await page.goto('https://en.wikipedia.org/wiki/Main_Page');

        await browser.close();
    } catch (err) {
        console.error(err);
    }
})();

FWIW: It reproduces for me on macOS Sierra (10.12.6):

$ node pup.js 
Error: Evaluation failed: DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.
    at <anonymous>:1:10
    at ExecutionContext.evaluateHandle (node_modules/puppeteer/lib/ExecutionContext.js:81:13)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)