Below is the simple method to get absolute URL using javascript. This code can be run on the Browser Console directly. Open the developer tools and navigate to console tab and paste the below function to test the snippet.
Sample Code Get Absolute URL using Javascript
var getAbsoluteUrl = (function() {
var a;
return function(url) {
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
};
})();
// Sample Result based on the input.
getAbsoluteUrl('/'); //Returns https://itsmycode.com/
//Returns https://itsmycode.com/get-absolute-url-using-javascript
getAbsoluteUrl('/get-absolute-url-using-javascript');
How to read the current URI in parts?
Let us take an example of the current URL https://itsmycode.com/get-absolute-u…ing-javascript/
location.protocol = "http:"
window.location.host = "itsmycode.com"
window.location.pathname="/get-absolute-url-using-javascript/"
To get the complete URL, we can concat the above code as shown below.
var myURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
1 comment
Absolutely Useful! Thank you very much.