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 ( 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);

// 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