1 应用背景
通常我们希望在页面加载一些脚本然后获取脚本生成的cookie。这里考虑使用page.setContent方法,其中script标签内部包含设置cookie的代码。最后通过执行document.cookie来获取cookie。
(async () => {
const browser = await puppeteer.launch({
"executablePath": "路径",
"headless": false
});
try {
let page = await browser.newPage();
await page.setContent("<script>...</script>")
let cookie = await page.evaluate(() => document.cookie);
console.log("cookie :" + cookie);
} catch (e) {
console.log(e);
} finally{
await browser.close();
}
})();
2 产生的问题与解决方式
按1中设想方式,最终会产生如下错误。
Error: Evaluation failed: DOMException: Failed to read the 'cookie' property from 'Document': Access is denied for this document.
at __puppeteer_evaluation_script__:1:17
at __puppeteer_evaluation_script__:1:17
at ExecutionContext.evaluateHandle
由于使用访问页面后再获取执行document.cookie可以正常调用,因此变通方法可以通过增加goto调用 page.goto(“https://www.baidu.com/”); 跳转到某个页面后再次获取即可。
(async () => {
const browser = await puppeteer.launch({
"executablePath": "/Users/Hello/Documents/chrome-mac/Chromium.app/Contents/MacOS/Chromium",
"headless": false
});
try {
let page = await browser.newPage();
await page.goto("https://www.baidu.com/");
await page.setContent("<script>...</script>")
let cookie = await page.evaluate(() => document.cookie);
console.log("cookie :" + cookie);
} catch (e) {
console.log(e);
} finally{
await browser.close();
}
})();