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

internet-explorer-6javascripturl

I'm currently using the following function to 'convert' a relative URL to an absolute one:

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

This works quite well in most browsers but IE6 insists on returning the relative URL still! It does the same if I use getAttribute('href').

The only way I've been able to get a qualified URL out of IE6 is to create an img element and query it's 'src' attribute – the problem with this is that it generates a server request; something I want to avoid.

So my question is: Is there any way to get a fully qualified URL in IE6 from a relative one (without a server request)?


Before you recommend a quick regex/string fix I assure you it's not that simple. Base elements + double period relative urls + a tonne of other potential variables really make it hell!

There must be a way to do it without having to create a mammoth of a regex'y solution??

Best Answer

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.