BASE HREF, javascript, and Internet Explorer vs. Firefox

ElBel picture ElBel · Mar 10, 2009 · Viewed 17.6k times · Source

Question:

IE and Firefox / Safari seem to deal differently with BASE HREF and Javascript window.location type requests. First, is this an accurate description of the problem? What's going on? And what's the best cross-browser solution to deal with this situation?

Context:

I have a small PHP flat file sitelet (it's actually a usability testing prototype).

I dynamically generate the BASE tag's HREF value in PHP, i.e. if it's running on our company's server, it's:

$basehref = 'http://www.example.com/alpha/bravo/UsabilityTest/';

and on my local dev machine, it's:

$basehref = 'http://ellen.local/delta/echo/foxtrot/UsabilityTest/';    

For one of the tasks, I collect some user input, do some transformations on it in Javascript, and send to the server using code like this:

function allDone() {
    // elided code for simplicity of stackoverflow question
    var URI = "ProcessUserInput.php?";
    URI = URI + "alphakeys=" + encodeURI( keys.join(",") );
    URI = URI + "&sortedvalues=" + encodeURI( values.join(",") );
    window.location = URI;
}

Both the javascript file (containing function allDone()) and the processing PHP script (ProcessUserInput.php) live in a subdirectory of UsabilityTest. In other words, their actual URL is

http://www.example.com/alpha/bravo/UsabilityTest/foxtrot/ProcessUserInput.php aka

$basehref . '/foxtrot/ProcessUserInput.php'

The Problem

IE's JavaScript basically seems to ignore the BASE HREF. The javascript and the PHP processor live in the same directory, so the call to ProcessUserInput.php works out fine. The input gets processed and everything works fine.

But when I test on Firefox, the JavaScript does appear to use the BASE HREF, because the script's output gets sent to

$basehref . '/ProcessUserInput.php'

This breaks, because ProcessUserInput.php is in a subdirectory of basehref. However, if I add the subdirectory name to the javascript, it no longer works in IE.

Solutions?

I can think of a few ways to solve this:

  • In Javascript, read the HREF property of the BASE tag and manually prepend to var URI in the javascript, calling a fully-resolved absolute URL
  • Process the .js file with PHP and insert the $basehref variable into the script
  • Move the files around
  • Something else?

I'm sure there must be other ways to solve this too. What's the best way to deal with BASE HREF in JavaScript when IE and Firefox apply it differently in JavaScript?

Answer

ElBel picture ElBel · Mar 11, 2009

Using the assign method of window.location seems like the most straightforward answer.

Instead of

window.location = URI;

I'm using this:

window.location.assign( URI ); 

which is doing the right thing in both IE and Firefox.