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 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.
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.
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.
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); })();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With