Reputation: 503
I would like to automate printing a number of URLs. Headless Chrome works beautifully here ...
chrome --headless --disable-gpu --print-to-pdf="C:\tmp\test.pdf" https://time.com/
Except that the real site I want to run this on requires authentication. I was hoping that headless Chrome would share cookies with Chrome and therefore all will be hunky-dory. But I am wrong. The print indicates that JavaScript are cookies are disabled, so I can't print what I want.
Appreciate if someone could help me solve this! Many thanks in advance!!
Upvotes: 5
Views: 1542
Reputation: 464
I managed cookie for chrome headless (command line) by specific where cookie store path.
First thing first, Chrome manages its cookie using sqlite file, where it encrypts cookie value and stores.
We will make chrome headless DO NOT encrypt its cookie with option
--disable-cookie-encryption
and specific where chrome store its cookie database file with option.
--user-data-dir={exist_folder}
sqlite database will normally be stored in.
{exist_folder}/Default/Cookies
Open the database, and run an insert or update into cookies table with your favorite database tools. In my case it is LiteDB, php.
Each row will have host_key as domain, name as name of cookie, value as cookie value. Example:
|host_key|+ name |+++++++++++ value ++++++++++++++++++|
|time.com|_pubcid|c2017f65-0c2c-49e0-93e4-e9b8b34f2879|
Now the total command to run chrome headless with prepared cookies is.
chrome --headless --disable-gpu --disable-cookie-encryption --user-data-dir="{exist_folder}" --print-to-pdf="C:\tmp\test.pdf" https://time.com/
Upvotes: 1