Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

javascript - How to specify browser language in Puppeteer

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 a Preferences file a { "intl": { "accept_languages": "es" } } but the browser Settings - Languages still don't show Spanish and neither does window.navigator.languages neither window.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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

es bn

BrowserLeaks:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...