How can an external JavaScript determine the URL from which it was included?

Viewed 26

I have an external JavaScript file and I'd like to know the src attribute value URL that was used to include it in the tag from the HTML document. For example:

<script src='https://foo.bar/baz.js'><script>

And then inside baz.js I'd like to write this code:

let mysrc = getMySrc() // Should return https://foo.bar/baz.js

Is it possible to write a getMySrc() function that does this?

2 Answers

Use:

const src = document.currentScript.getAttribute('src');

This works because document.currentScript will refer to the script tag corresponding to the currently running script.

In addition to the answer by @CertainPerformance. To get the resolved URL and not just what the script parameter stated:

const url = document.currentScript.src;

To get the directory where it originated:

let url = new URL(document.currentScript.src);
const dir = url.origin + url.pathname.replace(/\/[^\/]+$/, '/');
Related