[英]onBeforeUnload not being triggered from a headless browser
I am using pupeteer to work with headless Chrome on nodeJS.我正在使用 pupeteer 在 nodeJS 上使用无头 Chrome。
I am navigating through a local website and scraping the content, reading all the anchor <a>
URLS and saving their content in files.我正在浏览本地网站并抓取内容,阅读所有锚<a>
URL 并将其内容保存在文件中。
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);
}
On the other hand, in my local website, for every page I am performing an AJAX call on另一方面,在我的本地网站中,对于我正在执行 AJAX 调用的每个页面
$(window).on("beforeunload", function() {
//AJAX call
};
I discovered that if I go through my website from a browser, this AJAX call is performed when I leave each page.我发现如果我从浏览器浏览我的网站,当我离开每个页面时都会执行这个 AJAX 调用。 But when I browse my website from a headless browser through the NodeJS code above, the AJAX call doesn't get called但是当我通过上面的 NodeJS 代码从无头浏览器浏览我的网站时,不会调用 AJAX 调用
To verify, I put the AJAX call in DOMContentLoaded
event and it was called from the headless browser.为了验证,我将 AJAX 调用放在DOMContentLoaded
事件中,它是DOMContentLoaded
头浏览器调用的。 So the problem is with onBeforeUnload
所以问题出在onBeforeUnload
It could be that in my nodeJS code I am not closing every page so the event is not being called.可能是在我的 nodeJS 代码中,我没有关闭每个页面,因此没有调用该事件。
I was wondering what can I changed the event to, to call AJAX last thing on a page both on headless browsers and normal browsers?我想知道我可以将事件更改为什么,以便在无头浏览器和普通浏览器的页面上调用 AJAX 的最后一件事?
从pptr v1.4.0 开始,您可以将runBeforeUnload
选项传递给page.close
方法:
await page.close({runBeforeUnload: true});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.