Puppeteerで3rd-party cookieを保存・利用したい場合の処理についてまとめました。ログイン処理がクロスサイトになっているWebページをPuppeteerで利用する場合など、以下で紹介するコードが必要になることがあります。
cookieのセーブ
cookieを保存するファイルをtmpdirに作る方針のコードです。別のパスに保存する場合はよしなに変更してください。
const os = require('os');
const path = require('path');
const fs = require('fs').promises;
/*(中略)*/
try {
const client = await page.target().createCDPSession();
const allBrowserCookies = (await client.send('Network.getAllCookies')).cookies;
const cookiePath = path.join(os.tmpdir(), 'cookies.json');
await fs.writeFile(cookiePath, JSON.stringify(allBrowserCookies, null, 2));
} catch(err) {
// do nothing
console.log(err)
}
このコードのポイントはCDP (Chrome DevTools Protocol)のメソッドを呼び出してcookieを取り出している部分です。page.cookies()
だと現在のURLに紐付いているcookieしか返してくれないので、3rd-party cookieが必要な場合は使えません。CDPのプロトコルメソッドNetwork.getAllCookies
なら全cookieを取り出せます。
cookieの読み込み・利用
cookieの読み込みは特に注意点はありません。
下記コードではファイルが見つからなかったときのエラーを無視していますが、仕事のコードならもう少し真面目にエラー処理を書いた方がいいと思います。
const os = require('os');
const path = require('path');
const fs = require('fs').promises;
/*(中略)*/
try {
const cookiePath = path.join(os.tmpdir(), 'cookies.json');
const cookiesString = await fs.readFile(cookiePath);
const cookies = JSON.parse(cookiesString);
await page.setCookie(...cookies);
} catch(err) {
// do nothing
console.log(err)
}