I have this javascript function that's supposed to open a different div in chrome than in other browsers. The proper div opens in firefox, internet explorer, safari, and chrome, but opera opens the chrome div instead of the other div. Is there a way to stop opera from performing the chrome function?

     function Browser() {
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

      if (is_chrome) {
        document.getElementById('chrome').style.display = 'block';
        document.getElementById('notchrome').style.display = 'none';
}
  }
有帮助吗?

解决方案

If you read here you can see that you can look for the OPR string to identify Opera.

http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond

For example you can include it in your test like this:

var userAgent = navigator.userAgent.toLowerCase();
var is_chrome = userAgent.indexOf('chrome') > -1 && userAgent.indexOf('opr/') == -1;

其他提示

not to offend you. But, I think, if you check if it is only chrome and not opera, would break for other custom browsers built on chrome platform. Example Chinese QQ browser.

Rather, you can check if user agent contains "Chrome" in it and navigator.vendor contains "Google Inc." This gives you chrome precisely.

var isChrome = navigator.userAgent.toLowerCase().search('chrome') != -1 && navigator.vendor.toLowerCase().search('google') != -1;

I use toLowerCase() inorder to keep things clean and subtle.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top