Getting an absolute URL from a relative one. (IE6 issue)

Solution 1:

How strange! IE does, however, understand it when you use innerHTML instead of DOM methods.

function escapeHTML(s) {
    return s.split('&').join('&amp;').split('<').join('&lt;').split('"').join('&quot;');
}
function qualifyURL(url) {
    var el= document.createElement('div');
    el.innerHTML= '<a href="'+escapeHTML(url)+'">x</a>';
    return el.firstChild.href;
}

A bit ugly, but more concise than Doing It Yourself.

Solution 2:

As long as the browser implements the <base> tag correctly, which browsers tend to:

function resolve(url, base_url) {
  var doc      = document
    , old_base = doc.getElementsByTagName('base')[0]
    , old_href = old_base && old_base.href
    , doc_head = doc.head || doc.getElementsByTagName('head')[0]
    , our_base = old_base || doc_head.appendChild(doc.createElement('base'))
    , resolver = doc.createElement('a')
    , resolved_url
    ;
  our_base.href = base_url || '';
  resolver.href = url;
  resolved_url  = resolver.href; // browser magic at work here

  if (old_base) old_base.href = old_href;
  else doc_head.removeChild(our_base);
  return resolved_url;
}

Here's a jsfiddle where you can experiment with it: http://jsfiddle.net/ecmanaut/RHdnZ/

Solution 3:

You can make it work on IE6 just cloning the element:

function qualifyURL(url) {
    var a = document.createElement('a');
    a.href = url;
    return a.cloneNode(false).href;
}

(Tested using IETester on IE6 and IE5.5 modes)

Solution 4:

I found on this blog another method that really looks like @bobince solution.

function canonicalize(url) {
    var div = document.createElement('div');
    div.innerHTML = "<a></a>";
    div.firstChild.href = url; // Ensures that the href is properly escaped
    div.innerHTML = div.innerHTML; // Run the current innerHTML back through the parser
    return div.firstChild.href;
}

I found it a little more elegant, not a big deal.

Solution 5:

URI.js seems to solve the issue:

URI("../foobar.html").absoluteTo("http://example.org/hello/world.html").toString()

See also http://medialize.github.io/URI.js/docs.html#absoluteto

Not testeed with IE6, but maybe helpful for others searching to the general issue.