1

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?

hanzichi
  • 609
  • 2
  • 12
  • 22

2 Answers2

1

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');
ArtemSky
  • 1,173
  • 11
  • 20
0

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');
T Tse
  • 786
  • 7
  • 19
  • in fact, it's not my answer. because the path may be a relative path, and what I want is the absolute one – hanzichi Feb 09 '18 at 02:15
  • If you mean the absolute path of the file inside the server, then I think you are out of luck. You can only edit the file when the client requests the file, which would make the question not related to javascript at all, but rather related to your web server of choice. – T Tse Feb 09 '18 at 02:36
  • Um.. how does the other answer fulfill what you need? The two answers are essentially the same thing (`getAttribute('src')`). The only difference is the way we get the script element from the document (`currentScript` vs `querySelector`). – T Tse Feb 09 '18 at 02:37
  • but the other solution can get the absolute path.. you can test it – hanzichi Feb 09 '18 at 05:17