How to get the domain name of a server that hosts a JavaScript file?
Jul 23, 2019 · by Tim Kamanin
It can be done in two steps:
1) Determine a JavaScript file URL with document.currentScript.
document.currentScript property returns the <script> tag of the currently processed JS file. So having that knowledge we can easily get current script's URL from src property of document.currentScript:
const jsFileUrl = document.currentScript.src;
2) Now we need to parse jsFileUrl to get the domain name:
To do this, I like using URL constructor (https://developer.mozilla.org/en-US/docs/Web/API/URL/URL). We can pass an URL to that constructor and get an object representing given URL with a bunch of useful properties:
const url = new URL(jsFileUrl);
console.log(url.host);
console.log(url.origin);
console.log(url.protocol);
// etc...
So if we put it as a one-liner, it would look like:
const getSrcOrigin = () => new URL(document.currentScript.src).origin;
Hope this helps!
Hey, if you've found this useful, please share the post to help other folks find it: