4
0

More than 3 years have passed since last update.

Puppeteerで3rd-party cookieを保存・利用する

Last updated at Posted at 2021-01-24

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)
    }

元ネタ

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0