Question

I'm trying to run a very simple browser detect script and it executes just fine in Safari and Chrome (running on a Mac) but doesn't execute at all in Firefox. I can boil it down to the simplest possible form, and it still doesn't execute:

<script type="text/javascript">
if (navigator.userAgent.match(/^.*Chrome.*$/)) {break;}
else {
location="howdy.html"
}
</script>

This has been perplexing me for hours now. Anyone have an idea? Thanks!!

Was it helpful?

Solution

Change location="howdy.html" to location.href="howdy.html"

And also, stop doing browser-sniffing. Do feature detection in your JavaScript to make a more robust application in the long-term.

OTHER TIPS

You are using the break statement in a wrong place, I'm sure you are getting a syntax error, since it's illegal to use break outside a loop or a switch.

ECMA-262 Spec. Reference:

12.8 The break Statement

Syntax

BreakStatement :

break [no LineTerminator here] Identifieropt ;

Semantics

A program is considered syntactically incorrect if either of the following is true:

  • The program contains a break statement without the optional Identifier, which is not nested, directly or indirectly (but not crossing function boundaries), within an IterationStatement or a SwitchStatement.

  • The program contains a break statement with the optional Identifier, where Identifier does not appear in the label set of an enclosing (but not crossing function boundaries) Statement.

This is just a side issue, but it's too big for a comment.

Looking at your regex, I have to think there's something wrong there. .* matches everything, and since regular expressions are greedy by default the first .* would match on the entire rest of the string, leaving no chance to match the Chrome part and forcing a failure. Some engines might be smart enough understand what you mean, but I would still simplify that to just /Chrome/.

If me, I will do like this

if(!/Chrome/.test(navigator.userAgent)) 
   location.href="howdy.html";

I use this code to tag errors logged when I'm testing code on multiple browsers.

It gets the browser name and version right for the browsers I test on-IE, Safari, Firefox, Opera, Chrome. But I call it navigator.sayswho because that's all it is- who the navigator says it is.

navigator.sayswho= (function(){
 var N= navigator.appName, ua= navigator.userAgent, tem;
 var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
 if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
 M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
 return M;
})();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top