Puppeteer cookie 不适用于 page.setContent()

Puppeteer cookies not working with page.setContent()

提问人:Justin Fiedler 提问时间:11/18/2023 更新时间:11/18/2023 访问量:8

问:

使用 时,我无法让 Cookie 在 Puppeteer 中工作。page.setContent()

当我尝试访问 Cookie 时,我收到错误。DOMException: Failed to read the 'cookie' property from 'Document': Access is denied for this document.

var filePath = path.join(__dirname, '../assets/index.html')
var contentHtml = fs.readFileSync(filePath, 'utf8');

const browser = await puppeteer.launch({
  headless: "new",
});
const page = await browser.newPage();
await page.setJavaScriptEnabled(true);
page.on('console', msg => console.log('PAGE LOG:', msg.text()));
  
await page.setContent(contentHtml);
await page.evaluate(async () => {
  // This throws an error
  // DOMException: Failed to read the 'cookie' property from 'Document': Access is denied for this document.
  console.log(`cookies`, document.cookie);
});
await browser.close();
饼干 傀儡师

评论


答:

0赞 Justin Fiedler 11/18/2023 #1

我能够通过使用来解决该问题

await page.goto(`file://${filePath}`);

而不是await page.setContent(contentHtml);