Skip to content

Instantly share code, notes, and snippets.

@zirkelc
Last active May 18, 2024 07:30
Show Gist options
  • Save zirkelc/0344ebdaaab14f234bfb3a3d23bd5f03 to your computer and use it in GitHub Desktop.
Save zirkelc/0344ebdaaab14f234bfb3a3d23bd5f03 to your computer and use it in GitHub Desktop.
Puppeteer: set browser language for Chrome
/*
* There are multiple options to affect the user language on Chrome.
*/
const LANG = 'de';
/*
* Set `--lang=de'` when starting Chrome
* https://peter.sh/experiments/chromium-command-line-switches/#lang)
*/
const args = [...puppeteer.defaultArgs(), `--lang=${LANG}`];
/*
* Set env variable `LANG` when starting Chrome
* https://issues.chromium.org/issues/40535085#comment15
* https://github.com/puppeteer/puppeteer/issues/5970#issuecomment-690677674
* https://stackoverflow.com/a/71255152/1967693
*/
const env = {
//! Note: setting this env caused Chrome to fail on certain operating systems
LANG: LANG,
};
const browser = await puppeteer.launch({
args,
executablePath: puppeteer.executablePath(),
headless: true,
ignoreHTTPSErrors: true,
env,
});
const page = await browser.newPage();
/*
* Set HTTP `Accept-Language` header for page
* https://stackoverflow.com/a/47292022/1967693
*/
await page.setExtraHTTPHeaders({
'Accept-Language': LANG,
});
/*
* Override `navigator.language` on the page
* https://pptr.dev/api/puppeteer.page.evaluateonnewdocument/#example
*/
await page.evaluateOnNewDocument((lang) => {
Object.defineProperty(navigator, 'language', {
get() {
return LANG;
},
});
Object.defineProperty(navigator, 'languages', {
get() {
return [LANG];
},
});
}, LANG);
/*
* Override language with Chrome DevTools Protocol
* https://stackoverflow.com/questions/78481847/puppeteer-and-chrome-change-browser-language-without-restart
* https://chromedevtools.github.io/devtools-protocol/1-3/Network/#method-setUserAgentOverride
*/
const cdpSession = await page.createCDPSession();
cdpSession.send('Network.setUserAgentOverride', {
userAgent: await browser.userAgent(),
acceptLanguage: LANG,
});
await page.goto(url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment