Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let IE support html base tag with relative href? like: `<base href="../"></base>`

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.

like image 229
Freewind Avatar asked Feb 11 '12 03:02

Freewind


People also ask

How do you define an HTML base tag to specify base URL for all relative URLs in a document?

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.

What is the use of base href in HTML?

The HTML | <base> href Attribute is used to specify the base URL for all the relative URL of a page.

How you define the base URL in put call?

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.

What is used to establish the base URL?

The <base> HTML element specifies the base URL to use for all relative URLs in a document.


1 Answers

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.

like image 148
Cheery Avatar answered Nov 15 '22 07:11

Cheery