我正在使用 pupeteer 在 nodeJS 上使用 headless Chrome。
我正在浏览本地网站并抓取内容,阅读所有 anchor <a>
URLS 并将其内容保存在文件中。
const puppeteer = require('puppeteer');
const { URL } = require('url');
const fse = require('fs-extra');
const path = require('path');
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
//Navigate to local website
await page.goto('http://localhost:5976/',{"waitUntil": "networkidle0"});
//Gather all anchors on my webpage and save their URLs in an array
const hrefs = await page.evaluate(() => {
const anchors = document.querySelectorAll('a');
return [].map.call(anchors, a => a.href);
});
browser.close();
//Loop through all the URLs and call them
for (var i = 0; i < hrefs.length; i++) {
start(hrefs[i]);
}
})
//Function to browse URL
async function start(urlToFetch) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('response', async (response) => {
//Treat content of page
});
await page.goto(urlToFetch, {
waitUntil: 'networkidle2'
});
setTimeout(async () => {
await browser.close();
}, 60000 * 4);
}
另一方面,在我的本地网站中,我对每个页面执行AJAX调用
$(window).on("beforeunload", function() {
//AJAX call
};
我发现如果我从浏览器浏览我的网站,这个 AJAX 调用会在我离开每个页面时执行。 但是当我通过上面的 NodeJS 代码从 headless 浏览器浏览我的网站时,不会调用 AJAX 调用
为了验证,我将 AJAX 调用放在 DOMContentLoaded
中事件,它是从 headless 浏览器调用的。所以问题出在onBeforeUnload
可能是因为在我的 nodeJS 代码中我没有关闭每个页面,所以事件没有被调用。
我想知道我可以将事件更改为什么,以便在 headless 浏览器和普通浏览器的页面上最后调用 AJAX?
最佳答案
自 pptr v1.4.0 ,您可以将 runBeforeUnload
选项传递给 page.close
方法:
await page.close({runBeforeUnload: true});
关于javascript - onBeforeUnload 没有被 headless 浏览器触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50832325/