Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing localStorage with Puppeteer and no url

I'm creating a new page with page = browser.newPage(). I then set the html content with page.setContent(...) which includes a script.

After the script has loaded I make a call to it which somewhere down the line tries to make use or localStorage at which point I get an access denied error:

Error: Evaluation failed: DOMException: Failed to read the 'localStorage' property from 'Window': Access is denied for this document.

From my understanding, this is because in order to write to localStorage, one has to have an origin set - which in my case I do not.

If I change my code to first navigate to a url page.goto('http://localhost') and then do the html injection, I can write to localStorage without any issue.

Is there a way to write to localStorage without having to hit an existing URL first?

like image 825
Jay Avatar asked Jan 15 '18 14:01

Jay


1 Answers

For anyone struggling with this in the future. It is not possible to set localstorage data without an origin. If you can't navigate to a page though you can use the request interception described here. This is also a lot faster than calling a random page in the web.

await page.setRequestInterception(true)
page.on('request', request => {
  request.respond({ status: 200, contentType: 'text/html', body: '' })
})
await page.goto('http://127.0.0.1')

After that you're able to set the localstorage for that page.

like image 122
firefox2005 Avatar answered Oct 19 '22 18:10

firefox2005