Converting a raw cookie to be accepted by puppeteer

て烟熏妆下的殇ゞ 提交于 2019-12-11 05:36:45

问题


I want to pass session from passport.js to puppeteer.

I used var cookies = req.cookies; in order to get the cookies value.

I console.logged it and it is something like this:

{ 'connect.sid': 's:qX4ZrttrjydtrjkgsdghsdghrewynZj4Ew2OUh.tTSILkcvgsegsegsegsr99gmW5
0XLcJefM' }

I thought that it would be as easy as to pass this value to puppeteer.

But puppeteer has a page.setCookie() function that its format is this:

page.setCookie(...cookies)
...cookies <...Object>
name <string> required
value <string> required
url <string>
domain <string>
path <string>
expires <number> Unix time in seconds.
httpOnly <boolean>
secure <boolean>
sameSite <string> "Strict" or "Lax".
returns: <Promise>

So how do i pass puppeteer my cookie? Is there a way to convert it from its raw value to the one that puppeteer accepts?

Maybe is that large string on my raw cookie, the value to pass to the object that puppeteer accepts?


回答1:


If you are on MacOS (unfortunately I cannot currently comment to ask), I was searching for an answer to this problem for quite a while too.. and the answer is the cookie value is encrypted with your MacOS user credentials into an SQL DB table, which you need to first decrypt with something that can access your keychain (with your permission of course).

Once that is decrypted, part 2) is converting that into something Puppeteer will accept.

There's an NPM package that does the former, but not the latter (https://github.com/bertrandom/chrome-cookies-secure), but I've worked on it so that it does now generate Puppeteer ready cookies for any given Chrome profile. There is a PR request in for it (https://github.com/bertrandom/chrome-cookies-secure/pull/14) - not yet accepted - but I have had it running on a live app for a month.

Add the NPM Package for chrome-cookies-secure to your application and you'll be on your way.

The nuts and bolts of creating the Puppeteer object are as follows (you should be able to see the changes in index.js to the open PR, plus example in the README.MD):

// 'cookie' is an array of Objects with keys as written in decrypted SQL DB

let puppeteerCookies = [];

cookies.forEach(function(cookie, index) {
    const puppeteerCookieObject = {
        name: cookie.name,
        value: cookie.value,
        expires: cookie.expires_utc,
        domain: cookie.host_key,
        path: cookie.path
    }
    if (cookie.is_secure) {
        puppeteerCookieObject['Secure'] = true
    }
    if (cookie.is_httponly) {
        puppeteerCookieObject['HttpOnly'] = true
    }
    puppeteerCookies.push(puppeteerCookieObject)
})

return puppeteerCookies;

Hope this helps.



来源:https://stackoverflow.com/questions/50399708/converting-a-raw-cookie-to-be-accepted-by-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!