Puppeteer to listen for map.on('load') from within Node

无人久伴 提交于 2019-12-11 19:07:13

问题


Using Puppeteer to listen for map.on('load') from within Node.

(async () => {
  const browser = await puppeteer.launch({ headless: false, devtools: true });
  const page = await browser.newPage();

  function nodeLog(msg) {
    console.log(msg);
  }

  page.on('load', async () => {
    await page.evaluate(() => {
      window.map.on('load', () => {
        console.log("This runs on the index.html js but I do not need that");
        nodeLog("WHY IS THIS NOT WORKING??")
      })
    })
  });

  await page.goto(`file:${__dirname + '/index.html'}`);

})();

回答1:


I also figured out how to return information. I reread the docs and got some understanding. I was not understanding the context.

const nodeLog = msg => console.log;
const msg = await page.evaluate(() => { return 'this is working' });

nodeLog(msg);



回答2:


waitForSelector should work, eg. when using a selector from the readily rendered map... or listen for the map.bounds_changed or the map.idle event, which are triggered once the map is fully loaded. The map.load event might happen too soon.

Here's a working example, which I've just put together:

const puppeteer = require('puppeteer');
const url = 'https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/full/map-simple';

run().then(() => {
    console.log('entering asynchronous execution.')
}).catch(error => {
    console.log(error)
});

async function run() {
  puppeteer
    .launch({devtools: true, headless: false})
    .then(async browser => {

      const page = await browser.newPage();
      await page.goto(url);

      await page.evaluate(() => {
        window.map.addListener('idle', function(){
          console.log('the map is idle now');
          var div = document.createElement('div');
          div.setAttribute('id', 'puppeteer-map-idle');
          window.document.body.append(div);
        });
      });

      await page.waitForSelector('#puppeteer-map-idle' , {
        timeout: 5000
      }).then((res) => {
        console.log('selector #puppeteer-map-idle has been found.');

        /* in here the map should be fully loaded. */

      });

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

Admittedly that's kind of workaround, but the DOM manipulation can be observed.



来源:https://stackoverflow.com/questions/58104413/puppeteer-to-listen-for-map-onload-from-within-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!