Search code examples
javascripthtmlurlfragment-identifier

URL fragments and the BASE tag


I'm using the <base> tag in an application to simplify development.

I'm aware of the "feature" that occurs when an anchor is only a URL fragment, as in it routes to the <base> URL + fragment.

What can I do to circumvent that? I've never fudged with window.location or anything in Javascript, and rather than hack around for awhile at it, I assume someone knows of a quick-and-dirty, or an example.

Can this be circumvented? If so, please advise.

(I hate asking questions that suggest no attempt has been made, but I've been searching/reading to little avail)

(Also; using jQuery, so any examples that would take advantage of vanilla Javascript or jQuery are welcome)


jQuery solution I hacked together, not sure if its viable as a permanent solution though, thoughts?

$('a').each(function(index){
    if($(this).attr('href').indexOf('#') == 0){
        $(this).attr('href', (window.location.href).replace(/#.*$/, '')
            + $(this).attr('href'));
    }
});

Solution

  • Ok, so, I think I understand the question now.

    This has been tested in Google Chrome and Firefox.

    Add this javascript at the end of the body:

    base=document.getElementsByTagName("base"); 
    base=base[0].href;
    
    links=document.getElementsByTagName('a');
    
    for(index in links){
        if(links[index].href.indexOf(base+"#")==0){
            links[index].href=document.location+links[index].href.slice(links[index].href.indexOf("#"));
        }
    }