How to get the domain name of a server that hosts a JavaScript file?

23 Jul ยท by Tim Kamanin ยท 1 min read

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!

Want to get more ๐Ÿ”ฅ tips like this one?

Subscribe to get notified about new dev tutorials