开发者

How do I change the browser language with Javascript

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)


You can detect, but cannot set.

var lang = navigator.language || navigator.userLanguage;

// navigator.language     : Netscape & Firefox
// navigator.userLanguage : Internet Explorer


If you want to output different languages, the best way is to do it server-side. Either:

  • use an AJAX call to dynamically load the appropriate page
  • use a session variable to load the initial page correctly


This is impossible and a bad idea. A better idea is to detect the browser's language, which is possible to do reasonably well, and ask the user to change it (assuming the change is absolutely necessary).


No that is not possible. How would you find it if you open a page, and your browser turns Arabic (or some other language you can't read)?


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.


If what you actually want to do is detect the language the user is using, which is what you want to do, because nothing will annoy your visitors more that their browser preferences getting changed, on the server-side, read the Accept-Language HTTP request header that all modern browsers send, it should contain all the info you need. If it is absent, assume the language of your largest audience.

Check out RFC2616 Section 14.4 for more information on Accept-Language and it's use.


This is definitely not possible using JavaScript on a web page.

A browser Extension might have the rights to change this - I'm not sure, it will also depend on the browser. However, building such an extension would require a fair amount of skill and work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜