How do I change the browser language with Javascript

Viewed 33789

I want to access the user browser settings and change the browser language, is this possible using Javascript?

If it's possible, how can I access this? (sample code please)

6 Answers

This is possible if you do it from within a Chrome extension.

Check this answer to a similar question & contentScript.js of locale-switcher Chrome extension:

let locale = null;

chrome.storage.local.get(["locale"], result => {
  if (result) {
    locale = result.locale;
  }

  if (locale) embedScript();
});

const embedScript = () => {
  const code = `
    (() => {
      Object.defineProperties(Navigator.prototype, {
        language: {
          value: '${locale}',
          configurable: false,
          enumerable: true,
          writable: false
        },
        languages: {
          value: ['${locale}'],
          configurable: false,
          enumerable: true,
          writable: false
        }
      });
    })();`;

  const script = document.createElement("script");
  script.textContent = code;
  document.documentElement.prepend(script);
  script.remove();
};

I'm aware of timing (this question was asked 10 years before this answer) & that would be particularly fun if you are the author of this extension.

Related