Home | About | rss

Fixing Base Href Javascript Document.Location For Internet Explorer

 
IE(6) behaves differently to Firefox, Safari and Opera in two seperate ways with regards to

 <base href="http://example.com/" />

First, if you do:

  <script type="text/javascript">
    document.location.href = '/new/location';
  </script>

IE will ignore the base href. The others honour it. IE is plain wrong.

Second, if you have:

 <base href="http://example.com" />

which presumably (and pedantically) is missing the trailing slash from the end of the domain (.com rather than .com/)

  <script type="text/javascript">
    alert(document.getElementsByTagName('base')[0].href);
  </script>

will tell you that Firefox, Opera and Safari automagically correct the error and return a domain with the slash appended on the end. IE doesn't bother.

Not sure if IE is wrong, or has chosen a different way to resolve an ambiguous case.

In any event, this bites you if you care about not having double slashes in urls when you try to fix the first problem.

And thus if you are using javascript to navigate based on a form select box such as:

 <form>
   <select onchange="handler(this)">
     <option value="/relative/url">go there</option>
   </select>
 </form>

You are going to need some IE fixing magic such as:

 // loc is the relative path your wish to redirect to
 var b = document.getElementsByTagName('base');
 if (b && b[0] && b[0].href) {
   if (b[0].href.substr(b[0].href.length-1) == '/' && loc.charAt(0) == '/')
     loc = loc.substr(1);
   loc = b[0].href + loc;
 }
 location.href = loc;

see also