Jul 23, 2019 · by Tim Kamanin
It can be done in two steps:
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
const jsFileUrl = document.currentScript.src;
jsFileUrlto 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: