Set localstorage items before page loads in puppeteer?

Set localstorage items before page loads in puppeteer?

puppeteer get localstorage
puppeteer set cookie
puppeteer api
puppeteer-core
puppeteer executablepath
puppeteer tutorial
puppeteer debug
page setviewport

We have some routing logic that kicks you to the homepage if you dont have a JWT_TOKEN set... I want to set this before the page loads/before the js is invoked.

how do i do this ?


You have to register localStorage item like this:

await page.evaluate(() => {
  localStorage.setItem('token', 'example-token');
});

You should do it after page page.goto - browser must have an url to register local storage item on it. After this, enter the same page once again, this time token should be here before the page is loaded.

Here is a fully working example:

const puppeteer = require('puppeteer');
const http = require('http');

const html = `
<html>
  <body>
    <div id="element"></div>

    <script>
      document.getElementById('element').innerHTML = 
        localStorage.getItem('token') ? 'signed' : 'not signed';
    </script>
  </body>
</html>`;

http
  .createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write(html);
    res.end();
  })
  .listen(8080);

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto('http://localhost:8080/');

  await page.evaluate(() => {
    localStorage.setItem('token', 'example-token');
  });

  await page.goto('http://localhost:8080/');

  const text = await page.evaluate(
    () => document.querySelector('#element').textContent
  );

  console.log(text);
  await browser.close();

  process.exit(0);
})();

[Feature request] ability to set localStorage/sessionStorage w/o , We cannot set local or session storage w/o first loading a page from the target we use these then to contextually set storage before loading the target page. It would be great if Puppeteer could set storage generally or for a  There's some discussion about this in Puppeteer's GitHub issues. You can load a page on the domain, set your localStorage, then go to the actual page you want to load with localStorage ready. You can also intercept the first url load to return instantly instead of actually load the page, potentially saving a lot of time.


There's some discussion about this in Puppeteer's GitHub issues.

You can load a page on the domain, set your localStorage, then go to the actual page you want to load with localStorage ready. You can also intercept the first url load to return instantly instead of actually load the page, potentially saving a lot of time.

const doSomePuppeteerThings = async () => {
  const url = 'http://example.com/';
  const browser = await puppeteer.launch();
  const localStorage = { storageKey: 'storageValue' };
  setDomainLocalStorage(browser, url, localStorage);

  const page = await browser.newPage();
  // do your actual puppeteer things now
};

const setDomainLocalStorage = async (browser, url, values) => {
  const page = await browser.newPage();
  await page.setRequestInterception(true);
  page.on('request', r => {
    r.respond({
      status: 200,
      contentType: 'text/plain',
      body: 'tweak me.',
    });
  });
  await page.goto(url);
  await page.evaluate(values => {
    for (const key in values) {
      localStorage.setItem(key, values[key]);
    }
  }, values);
  await page.close();
};

Not allowed to access local storage. · Issue #1002 · puppeteer , when I attempt to access local storage I get the following error. wait for the page to load before executing my evaluation function. waiting one  26 Set pupeteer window size when running not headless (not viewport) Feb 8 '18 23 Source Maps not working with Webpack Jun 20 '16 21 How to disable HTTP/2 in chrome or chromium?


Try and additional script tag. Example:

Say you have a main.js script that houses your routing logic.

Then a setJWT.js script that houses your token logic.

Then within your html that is loading these scripts order them in this way:

<script src='setJWT.js'></script>
<script src='main.js'></script>

This would only be good for initial start of the page.

Most routing libraries, however, usually have an event hook system that you can hook into before a route renders. I would store the setJWT logic somewhere in that callback.

Headless browser - Puppeteer [Gerardnico, This article shows how to run headless Chrome and Puppeteer as part of your web server to "SSR" a static version of client-side JS apps for improved loading Products · Web · Tools for Web Developers · Puppeteer This ensures that the posts exist in the DOM before we dump the serialized page. Can Puppeteer store values from sessionStorage and localStorage on a disk and use them next time?


Headless Chrome: an answer to server-side rendering JS sites, Learn how to use localStorage and sessionStorage in your web apps. only until the window or tab is closed, while with localStorage the data is you can use JSON.stringify to store more complex objects and JSON.parse to read them: Marketplace · Load Balancers · Block Storage · Tools & Integrations  First, every time the form is submitted, the input value should be added to the localStorage as well as appear on the front end. We'll also want to loop through all the existing local storage items and display them at the top of the list. Last, we want the "Clear All" button to remove all items from local storage as well as the front end.


Introduction to localStorage and sessionStorage, Set localstorage items before page loads in puppeteer? Without requiring to double goTo this would work: const browser = await puppeteer.launch();  The setItem () method of the Storage interface, when passed a key name and value, will add that key to the given Storage object, or update that key's value if it already exists. storage .setItem ( keyName, keyValue ); A DOMString containing the name of the key you want to create/update. A DOMString containing the value you want to give the key


Headless Browser Examples with Puppeteer, Web Scraping with a Headless Browser: A Puppeteer Tutorial The code passed to the evaluate() method is pretty basic JavaScript that builds an array of objects a new page and waiting for the page to load before restarting the while loop. Puppeteer sets an initial page size to 800×600px, which defines the screenshot size. The page size can be customized with Page.setViewport(). Example - create a PDF. Save file as hn.js