【发布时间】:2018-09-07 11:16:29
【问题描述】:
使用 puppeteer,我无法弄清楚如何获取 document.readyState。我需要等到页面加载完毕后再渲染 pdf。
const browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox']
});
const page = await browser.newPage();
console.log('Setting HTML content...');
// Can't POST data with headless chrome, so we have to get the HTML and set the content of the page, then render that to a PDF
await page.setContent(html);
// Generates a PDF with 'screen' media type.
await page.emulateMedia('screen');
var renderPage = function () {
return new Promise(async resolve => {
await page.evaluate((document) => {
console.log(document);
const handleDocumentLoaded = () => {
console.log('readyState: ', document.readyState);
console.log('Rendering PDF...');
Promise.resolve(resolve(page.pdf({ path: thisPDFfileName, format: 'Letter' })));
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", handleDocumentLoaded);
} else {
handleDocumentLoaded();
}
});
// I also tried this... no luck
// setTimeout(async function () {
// console.log('Awaiting document...');
//
// const handle = await page.evaluateHandle(() => ({window, document}));
// const properties = await handle.getProperties();
// const windowHandle = properties.get('window');
// const documentHandle = properties.get('document');
// await handle.dispose();
//
// console.log('readyState: ', documentHandle.readyState);
// if ("complete" === documentHandle.readyState) {
// await documentHandle.dispose();
// console.log('readyState: ', doc.readyState);
// console.log('Rendering PDF...');
// resolve(page.pdf({ path: thisPDFfileName, format: 'Letter' }));
// } else {
// renderPage();
// }
// }), 250;
});
};
// Delay required to allow page to render JS before creating PDF
await renderPage();
await browser.close();
sendPdfToClient();
我尝试了evaluateHandle 并且只能获取innerHTML,而不是文档对象本身。
获取包含readyState 的document 对象的正确方法是什么?
最后,我应该为loaded或DOMContentLoaded设置一个监听器,我需要等到google maps JS渲染地图?如果需要,我可以发送自定义事件,因为我控制正在呈现的页面。
【问题讨论】:
标签: node.js async-await pdf-generation puppeteer google-chrome-headless