views:

729

answers:

3

I would like to block all users of Safari from visiting my flash game web site. I would like them to see a picture of someone being punched in the face instead of the games.

My understanding is that you can use JavaScript to do it, but I don't want to use some heavy framework like JQuery. Is there a way to do it in like a single line or two of JavaScript?

+23  A: 

This is a horrible, horrible idea IMO. I can understand the sentiment, but this is going to do as much good, and raise as much sympathy, as sites with "Stop using IE, moron!" messages. But it's up to you....

Quirksmode has a small BrowserDetect library that I trust has all the quirks worked out. If I were you, I would use that.

To do it in one line, look for Safari in the navigator.userAgent string.

Example code:

if (navigator.userAgent.indexOf('Safari/') != -1){
 alert("Safari detected");
}

If you want to make 100% sure you catch them all (well, 99% bearing in mind the user agent string can be changed freely by the client), you'd need to use a server-side language like PHP.

if (strstr($_SERVER["HTTP_USER_AGENT"], "Safari")) 
 {
  header("location:no-safari.html");
  die();
 }
Pekka
+1 for *"horrible, horrible idea"*. These types of "ideas" were particularly annoying for users who couldn't choose their web browser. Unfortunately, it is the will of some people to punish the users because a foolish/delusional view that the browser vendor will actually care.
Andy E
@Andy E yup. I'm all for protesting against Apple's policies - I find many of them horrible and unethical, too - but harassing your users isn't going to help. Never has.
Pekka
Thanks a million!This is perfect - by adding window.location="no-safari.html" instead of alert it moves the page too!
blank bank
@user you're welcome. I've added some more info.
Pekka
You can make this cleaner by not checking for iPad/iPhone/and iPod touch Safari user agent strings.
ireddick
"If you want to make 100% sure" << It doesn't make it 100%. You can very easily change the user agent string to whatever you like.
Oli
@Oli I mean, 100% sure in normal circumstances (i.e. when JavaScript is turned off.) It is still worth mentioning, good point, will edit.
Pekka
+1  A: 

if(navigator.appName == "Safari") { ....your code goes .... }

+2  A: 

More than a couple of lines but you could very simply cut this down so it only bothers with Safari: http://www.quirksmode.org/js/detect.html

A slightly more solid method would be to use a server-side detection method like php's get_browser([string $user_agent [, bool $return_array = false ]])

Needless to say, this is all a bit silly.

Oli