Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this user agent JavaScript not detect Opera correctly?

I wrote some JavaScript code to detect Opera, because my site uses a lot of HTML5 video in h.264 format, which Opera does not support. Instead of painstakingly transcoding my 100+ videos, I want to redirect Opera to a Flash version of the website.

This is the code I wrote, and it does not seem to work. Why is that? Sorry, I'm new to JavaScript.

 <script type="text/javascript">
    <!--
    if ((navigator.userAgent.match(/Opera/9.80/i))) {
    location.replace("http://mysite.com/flash");
    }
    -->
    </script>

P.S. PHP or other server-side language is not an option.

like image 405
user2170282 Avatar asked Sep 02 '26 18:09

user2170282


2 Answers

Your regular expression is incorrect. In JavaScript the / character is used to indicate the start and end of the regular expression, so if you want to use one as part of the pattern you need to escape it:

if ((navigator.userAgent.match(/Opera\/9.80/i))) {
like image 162
Anthony Grist Avatar answered Sep 04 '26 08:09

Anthony Grist


Not the answer you're looking for (in terms of how to test user agent) but a better solution (IMHO).

Have a look in to Modernizr and checking against video (with specific tests against h264).

Also, for what it's worth, there is a way to support video across devices.

EDIT As @PaulD.Waite pointed out, you can test support for this solely using the following code (from DiveIntoHTML5):

function VideoAndH264IsSupported(){
  var v = document.createElement('video');
  return !!(v.canPlayType && v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"').replace(/no/, ''));
}
like image 28
Brad Christie Avatar answered Sep 04 '26 08:09

Brad Christie