Home  >  Q&A  >  body text

Access javascript window variables in Puppeteer

<p>In my Puppeteer script, I use file JS to execute before loading the page: </p> <pre class="brush:js;toolbar:false;">const preloadFile = fs.readFileSync('./file.js', 'utf8'); const id = await page.evaluateOnNewDocument(preloadFile); </pre> <p>file.js contains: </p> <pre class="brush:js;toolbar:false;">const i = setInterval(()=>{ if (window.turnstile) { clearInterval(i) window.turnstile.render = (a,b) => { b.userAgent = navigator.userAgent window.tsCallback = b.callback window.action = b.action window.data = b.cData console.log(b) return 'foo' } } },50) </pre> <p>This script prints an object (Action, Cdata, Callback...) on the browser console</p> <p>I want to get this object from puppeter side and be able to call function callback(). </p> <p>I used page.evaluate() but it didn’t work for me</p>
P粉787806024P粉787806024380 days ago525

reply all(1)I'll reply

  • P粉193307465

    P粉1933074652023-09-05 12:27:00

    You can use my Puppeteer wrapper library https://github.com/wix-incubator/bubanai/pulls to achieve this goal (get the object from the browser console), use new ConsoleDriver(context).getMessages() method, and then convert the received object from the array to JSON...< /p>

    Or just copy the ConsoleDriver code into your project.

    refer to

    Usage examples

    reply
    0
  • Cancelreply