hanzichi
hanzichi

Reputation: 659

how to get the absolute path of an excuting js in the js?

for instance, the page of HTML contains the js, and the js's src is /js/test.js, and in this js file, can I get the string of /js/test.js while the js is excuted?

__dirname and process.cwd() can both do it in Node.js, but not work in js of broswer

can anyone help me?

Upvotes: 1

Views: 56

Answers (2)

T Tse
T Tse

Reputation: 846

In a browser, a script is loaded through HTTP request. The URI (the bits after the host name) does not necessarily correspond to the file name.

If you just want the src attribute, then you can refer to this answer, which recommends using document.currentScript to obtain the script element.

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

Upvotes: 0

ArtemSky
ArtemSky

Reputation: 1193

HTML

<script src="/some/path.js" id="script1"></script>
<script src="/some/path2.js" id="script2"></script>

JS

// /some/path.js
var path = document.querySelector('#script1').getAttribute('src');

// /some/path2.js
var path = document.querySelector('#script2').getAttribute('src');

Upvotes: 1

Related Questions