0

Here is my page:

<html>
<head>
<script src = "//myremoteserver.com/chat.js"></script>

<script>
var chat = new Chat();
</script>

How can I retrieve the url of the script inside the Chat class?

(answer : //myremoteserver.com/chat.js)

I tried:

window.location.origin; gives me the url of the current page document.getElementsByTagName('script') : do not provide url

aminography
  • 21,986
  • 13
  • 70
  • 74
yarek
  • 11,278
  • 30
  • 120
  • 219
  • have you tried `document.getElementsByTagName('script').src` ? – GBWDev Nov 06 '19 at 12:50
  • Does this answer your question? [JavaScript - How do I get the URL of script being called?](https://stackoverflow.com/questions/2976651/javascript-how-do-i-get-the-url-of-script-being-called) – GBWDev Nov 06 '19 at 12:52
  • You woon't be able to find out _which_ of the included scripts is running the code through code, as JS treats it all as a single big script and just adds more to the end. Its not aware of which file the code resided in through JS itself. – somethinghere Nov 06 '19 at 13:10

3 Answers3

0

You can access it by going through <head>.

document.getElementsByTagName("head")[0].getElementsByTagName("script")[0].src
Yarden Shoham
  • 201
  • 2
  • 9
0

You could give the script an id

<script id = "myScript" src = "//myremoteserver.com/chat.js"></script>
var element = document.getElementById('myScript');
console.log(element.src);

Can't see any reason why that wouldn't work.

Tom
  • 1,447
  • 1
  • 12
  • 26
0

Here is 2 ways to do this :

console.log(document.getElementsByTagName('script')[1].getAttribute("src"));
console.log(document.scripts[1].src);
<script src= "http://xxxxxxxxxxxxxxxxxxx"></script>
Ahmed Tag Amer
  • 1,381
  • 1
  • 8
  • 21