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 ( 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!

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓