Access javascript window variables in Puppeteer
P粉787806024
2023-09-04 23:32:41
<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>
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...Or just copy the ConsoleDriver code into your project.
refer to
Usage examples