How to specify browser language in Puppeteer
Solution 1
There are several ways to change locale, you can try all of them to find what works for you,
Use Args when launching
const browser = await puppeteer.launch({
headless: false,
args: ['--lang=bn-BD,bn']
});
Send the language as Header
await page.setExtraHTTPHeaders({
'Accept-Language': 'bn'
});
Forcefully set the language
// Set the language forcefully on javascript
await page.evaluateOnNewDocument(() => {
Object.defineProperty(navigator, "language", {
get: function() {
return "bn-BD";
}
});
Object.defineProperty(navigator, "languages", {
get: function() {
return ["bn-BD", "bn"];
}
});
});
For the sake of testing, I'll test this in multiple languages, including es
, and here is the result.
Google search:
BrowserLeaks:
Solution 2
There's an error in Md-Abu-Taher's answer.
The response to navigator.language
should return a string, not an array. Try it in your own browser console.
The code snippet should be:
await page.evaluateOnNewDocument(() => {
Object.defineProperty(navigator, "language", {
get: function() {
return "en-GB";
}
});
Object.defineProperty(navigator, "languages", {
get: function() {
return ["en-GB", "en"];
}
});
});
Giorgio
Updated on June 06, 2022Comments
-
Giorgio almost 2 years
I would like to launch a Google Chrome browser with language Spanish
es
using Puppeteer.I've tried
puppeteer.launch(args:['--lang=es',...],...)
but it didn't work.I've tried passing the environment variable
LANGUAGE=es mocha puppeteer-test.js
but it didn't work.I've tried using the
userDataDir
option and passing a folder with aPreferences
file a{ "intl": { "accept_languages": "es" } }
but the browser Settings - Languages still don't show Spanish and neither doeswindow.navigator.languages
neitherwindow.navigator.language
I'm using
Puppeteer 0.11.0
Node 8.4.0
NPM 5.2.0
macOS El Capitan 10.11.6
MacBook Pro Retina, 15-inch, Mid 2015 -
avalanche1 over 4 yearsMind you, that
args
solution doesnt work on mac os -
Aaron almost 4 yearsIs there another way for mac OS X?
-
Md. Abu Taher over 3 yearsThank you for pointing that out, I've updated my answer.
-
Petr Bodnár about 3 yearsAt Chromium issue 755338 they write that setting environment variable
LANG
should work as well on Linux. Nothing like that for Windows though, it seems...