木偶从Node内监听map.on('load')

时间:2019-09-25 18:20:35

标签: javascript node.js puppeteer

使用Puppeteer从Node内部监听map.on('load')。

(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'}`);

})();

2 个答案:

答案 0 :(得分:0)

waitForSelector应该可以工作,例如在使用容易呈现的地图中的选择器时...或监听map.bounds_changedmap.idle事件,这些事件在地图完全加载后触发。 map.load事件可能发生得太早。

这是一个有效的示例,我已经将其放在一起:

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();
    });
}

诚然,这是一种解决方法,但是可以观察到DOM操作。

答案 1 :(得分:0)

我还弄清楚了如何返回信息。我重新阅读了文档并获得了一些理解。我不了解上下文。

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

nodeLog(msg);