Getbaseurl() Javascript Call Function In A Href=""
I am calling the based url through javascript in a html page and I want to add the base url to call a link eg. Page The
Solution 1:
function getBaseURL () {
return location.protocol + "//" + location.hostname +
(location.port && ":" + location.port) + "/";
}
Edit: Addressed Mike Samuel's point on nonstandard ports.
Solution 2:
A general solution to allow for the use of <base>
(or not) - a further improvement would be to have the baseDocument removed from the baseURL using some kind of regex.
functiongetBaseURL () {
var baseURL = "";
var baseDocument = "index.html";
if (document.getElementsByTagName('base').length > 0) {
baseURL = document.getElementsByTagName('base')[0].href.replace(baseDocument, "");
} else {
baseURL = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/";
}
return baseURL;
}
Solution 3:
I am dealing with the same issue, and it isn't so much getting the base URL (as these answers have shown), but calling that javascript function from the element and then adding a relative path. Using @Christian Sanchez answer and other info I've found, this is an option using the onclick of the element:
JAVASCRIPT:
<scripttype="text/javascript">functiongetBaseURL(loc) {
return location.protocol + "//" + location.hostname +
(location.port && ":" + location.port) + "/" + loc;
}
</script>
HTML:
<ahref="filepath/index.html"onclick="getBaseURL(this.href);">TEST LINK</a>
Fiddle is here: http://jsfiddle.net/62g2bkyh/ (hover over link to see URL in fiddle - which shows base URL of iframe).
Post a Comment for "Getbaseurl() Javascript Call Function In A Href="""