0

I want to get the current js page URL where I am working. The js file is loaded from another domain.

If current domain is www.ab.com and the js file loaded from www.cd.com/test.js?parameter=123 in www.ab.com/product page.

How to get the URL (www.cd.com/test.js?parameter=123).

Please help

manas paul
  • 87
  • 7
  • Give your script tags an id. Then in the script, query the script element by the id, and read the src attribute. – Teemu Jan 27 '20 at 05:15
  • is there any other way to do this? – manas paul Jan 27 '20 at 05:20
  • Does this answer your question? [How to get the file-path of the currently executing javascript code](https://stackoverflow.com/questions/2255689/how-to-get-the-file-path-of-the-currently-executing-javascript-code) – Jesse Jan 27 '20 at 05:21
  • Why, that's a pretty much the only working way, considering you're not providing any practical iinformation of the scripts needing this information. The script in the answer Jesse has linked, works for some limited situations only, it fails when run in event listener handlers, or when one or more scripts are loaded asynchronously. – Teemu Jan 27 '20 at 05:21

2 Answers2

1

did you answer is it?

console.log($("#t1").attr("src"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="test.js?param=123" Id="t1"></script>
MBadrian
  • 409
  • 3
  • 10
1

There's no built in way to get that. The easiest way seems to get the <script> tag and parse its src attribute:

const script = document.currentScript
const url = script.src //"http://www.cd.com/test.js?parameter=123"

You could parse it with the URL API, to get an object like window.location:

const parsedUrl = new URL(url) //{ protocol: "http:", host: "www.cd.com", path: "/test.js", ...}
FZs
  • 16,581
  • 13
  • 41
  • 50
  • Note, that [`dcoument.currentScript`](https://developer.mozilla.org/en-US/docs/Web/API/Document/currentScript) has a very limited use case. – Teemu Jan 27 '20 at 05:34
  • @Teemu I've linked an SO post that lists methods to get the current script. – FZs Jan 27 '20 at 05:38
  • Then why not to vote to close as a duplicate instead of answering? Also, the docs I've linked, says: "_returns the [scriipt] which is currently being processed and isn't a JavaScript module ... will not reference the ` – Teemu Jan 27 '20 at 05:40
  • @Teemu I think, that's not really a duplicate, as it just tells how to get the script element itself, not that how yo get the URL of it (and maybe how to parse it) – FZs Jan 27 '20 at 05:43