Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a page's base href in Javascript?

I want to set a page's base href attribute in Javascript based off of the current hostname. I have generated HTML pages that can be viewed on different hostnames, which means generating a base href tag will work in one hostname but will be incorrect in the other.

like image 254
Zach Gardner Avatar asked Aug 16 '10 16:08

Zach Gardner


People also ask

Where should a base href be placed?

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 a base href?

The href attribute specifies the base URL for all relative URLs on a page.

How do you override a base in href?

The effect of the base tag is global to the document, and the only way to override the effect of <base href="..."> is to use absolute URLs. You can use window. location in JavaScript to get the URL of the page itself, in case the document was retrieved via HTTP. And you could use it to construct absolute URLs.

How do you define a base URL for a Web page in html5?

The HTML <base> tag is used to specify a base URI, or URL, for relative links. For example, you can set the base URL once at the top of your page in header section, then all subsequent relative links will use that URL as a starting point.


1 Answers

The correct way of doing this is to do a document.write of the tag based off the current hostname:

Correct:

<script type="text/javascript"> document.write("<base href='http://" + document.location.host + "' />"); </script> 

This method has produced correct results in IE, FF, Chrome, and Safari. It produces a (correct) different result than doing the following:

Incorrect:

<script type="text/javascript"> var newBase = document.createElement("base"); newBase.setAttribute("href", document.location.hostname); document.getElementsByTagName("head")[0].appendChild(newBase); </script> 
like image 96
Zach Gardner Avatar answered Oct 08 '22 01:10

Zach Gardner