Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set localstorage items before page loads in puppeteer?

Tags:

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 ?

like image 762
christoffee Avatar asked Aug 10 '18 14:08

christoffee


People also ask

How do I set my local storage puppeteer?

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.

Does localStorage persist after refresh?

localStorage demo Shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.

What is localStorage getItem?

The getItem() method returns value of the specified Storage Object item. The getItem() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorage object.


1 Answers

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); })(); 
like image 129
Everettss Avatar answered Oct 22 '22 18:10

Everettss