Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return window object using puppeteer

I'm trying to return the whole windows object from a page, and then traversing the object outside of puppeteer.

I'm trying to access the data in Highcharts property, for which I need to access the window object. The normal javascript code being something like window.Highcharts.charts[0].series[0].data.

I thought the easiest way would be to use puppeteer to access the site, and just send me back the windows object, which I could then use outside of puppeteer like any other JS object.

After reading the documentation, I'm finding it difficult to return the object as it would appear just putting 'window' into the chrome console. I'm not sure what I'm missing?

I've read through the documentation, and the following two methods seem like they should work?

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://www.example.com', {waitUntil: 'networkidle2'});

    // METHOD 1
    // Create a Map object
    await page.evaluate(() => window.map = new Map());
    // Get a handle to the Map object prototype
    const mapPrototype = await page.evaluateHandle(() => Map.prototype);
    // Query all map instances into an array
    const mapInstances = await page.queryObjects(mapPrototype);

    console.log(mapInstances);

    await mapInstances.dispose();
    await mapPrototype.dispose();

    // METHOD 2
    const handle = await page.evaluateHandle(() => ({window, document}));
    const properties = await handle.getProperties();
    const windowHandle = properties.get('window');
    const documentHandle = properties.get('document');
    var result = await page.evaluate(win => win, windowHandle);

    console.log(result)

    await handle.dispose();



    await browser.close();
})();

However, it only returns the following in the console, and not the simple object I would like;

enter image description here

Not sure if I'm going about this the right way, so any help/advice is much appreciated.

like image 459
alexc Avatar asked Jun 27 '18 14:06

alexc


1 Answers

Puppeteer's evaluate must return a serialisable object (otherwise it will return undefined, like in your case).

You can try the following approach (which actually uses Javascript's es6 proxy to let you use window inside your node test)

article:

https://medium.com/front-end-hacking/direct-javascript-access-in-puppeteer-391e48b5196b

Repo:

https://github.com/wix-playground/puppeteer-direct

like image 172
Yaniv Efraim Avatar answered Sep 21 '22 00:09

Yaniv Efraim