window.location on a Mac

Sometimes in JavaScript, you may want to redirect a user to another URL. This is often done setting the window.location properly like so:

window.location = "http://snook.ca/';

However, Safari and IE 5.2 for Mac (at least on OSX) behave a little differently than browsers on the PC. I put together this basic test page in order to see which scenarios work and which don't.

<script type="text/javascript">
function test3(){
  window.location = 'http://snook.ca/';
}
</script>
<p><a href="#" 
  onclick="window.location = 'http://snook.ca'">
  test 1</a></p>
<p><a href="#" 
  onclick="window.location = 'http://snook.ca'; 
      return false;">test 2</a></p>
<p><a href="#" 
  onclick="test3();">test 3</a></p>
<p><a href="#" 
  onclick="test3();return false;">test 4</a></p>
<p><a href="javascript:window.location = 
      'http://snook.ca';">test 5</a></p>

Tests 2, 4 and 5 work but 1 and 3 don't. And you can probably see why. In 1 and 3, we set the window.location to a new URL. This would normally redirect the user to the new page. But after the onclick event, it runs the URL contained in the href and overrides the redirect. In this case, the # keeps the page from redirecting altogether. By putting return false; we stop the href from being processed altogether.

Published June 09, 2004 · Updated September 17, 2005
Categorized as JavaScript
Short URL: http://snook.ca/s/165

Conversation

12 Comments · RSS feed
Ardi said on September 30, 2004

Thanks! I was stumped for a while as to why my JS was failing on stupid Macs. This helped.

Quix said on November 22, 2004

Thank you! I was pounding my head against the wall on this one.

ucantblemem said on January 04, 2005

Thank you so much!!! This seriously was giving major headaches!!!

Phil said on January 31, 2005

Thanks a million. I would have had a mjor problem on my hands without this information.

Jesse said on February 04, 2005

Thanks! this helped out a ton, I was stumped...and blaming it on MACs! ;)

Patrick said on February 04, 2005

Hallelujah!!!!!!

May Lilly said on April 07, 2005

Thank you sooooo much for posting this. It really helped me a lot!!!!

abearly said on April 21, 2005

now that's what the web is for. i was almost weeping for a solution. standardisation means i have to write better code!

Tim said on September 08, 2005

This information is very very helpful. It works perfectly with Mac IE5.2. But it does NOT work with Safari on Mac. I would appreciate it if you can give me some suggestion about Safari.

Jonathan Snook said on December 28, 2006

zadar: look into window.open or use target="_blank" on links.

alex said on November 08, 2008

kxZdtE fkjgh62vDfulv0s5FvSa

alan said on November 10, 2008

fSlZQM blkOpwF7nnBsJ42K7La

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.