I know according to the spec, the href
of base
should be a absolute URI.
href = uri [CT]
This attribute specifies an absolute URI that acts as the base URI for resolving relative URIs.
But firefox and chrome support relative URIs, e.g. ../../
, which is very important of my current project. I don't find a better solution other than "relative base href" for my project.
Is there any hacks or workgrounds for IE to let it support relative URIs? My web pages works well in firefox and chrome now, but it has to support IE.
The <base> tag specifies the base URL and/or target for all relative URLs in a document. The <base> tag must have either an href or a target attribute present, or both. There can only be one single <base> element in a document, and it must be inside the <head> element.
The HTML | <base> href Attribute is used to specify the base URL for all the relative URL of a page.
The URL found in the address bar of the front page of a website is its base URL. In other words, the common prefix found while navigating inside a given website is known as the base URL.
The <base> HTML element specifies the base URL to use for all relative URLs in a document.
Use this function to convert your URL to the absolute:
function toAbsURL(s) {
var l = location, h, p, f, i;
if (/^\w+:/.test(s)) {
return s;
}
h = l.protocol + '//' + l.host + (l.port!=''?(':' + l.port):'');
if (s.indexOf('/') == 0) {
return h + s;
}
p = l.pathname.replace(/\/[^\/]*$/, '');
f = s.match(/\.\.\//g);
if (f) {
s = s.substring(f.length * 3);
for (i = f.length; i--;) {
p = p.substring(0, p.lastIndexOf('/'));
}
}
return h + p + '/' + s;
}
You could use
var base = document.getElementsByTagName('base')[0];
base.href = toAbsURL(base.href);
Example http://jsfiddle.net/tEpkx/1/
Except that you have to detect the browser, too, and run it only for IE. Other browsers will get window.location updated by the href of the base
tag automatically and this code snippet will change it again. So write it as
<!--[if IE]>
<script type="text/javascript">
var base = document.getElementsByTagName('base')[0];
base.href = toAbsURL(base.href);
</script>
<![endif]-->
ps: <base />
is a single tag, it does not require the closing one.
Updated to include the port number if it is set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With