Search code examples
internet-explorerrelative-pathradix

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.


Solution

  • 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.