0

On my site mysite.com I load scripts from anothersite.com. Is there a way for a script running on mysite.com to know that it was downloaded from anothersite.com?

Ian Vink
  • 66,960
  • 104
  • 341
  • 555

3 Answers3

1

I found this to the the solution:

    function serverName() {

    var server = "";

    //IE and EDGE can't use the case-insensitive 'i' in this selector
    var path = $('script[src*="loader.js"]').attr('src'); //Look for the script tag of this script and get the URL

    var regex = RegExp('.*\/\/.*?\/'); // gets this: http://mysite/
    var m = regex.exec(path);
    if (m && m.length) {
        server = m[0].replace(/\/$/, "");//trim trailing slash
    }

    return server;
}
Ian Vink
  • 66,960
  • 104
  • 341
  • 555
-1

<!doctype HTML>
    <html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js" id="know"></script>
    </head>
    <body>
        Hello
        <script>
         const gebi=id=>document.getElementById(id)
         console.log(gebi('know').src)
        </script>
    </body>
    </html>

This would work

-2
const domain = location.hostname;

See more about location.hostname

The hostname property sets or returns the hostname of a URL.

Meghan
  • 1,215
  • 11
  • 17
  • Doesn't though tell me where the external script was loaded from, just eh consuming server. – Ian Vink Apr 27 '18 at 16:39
  • 1
    You may be looking for [`document.currentScript`](https://stackoverflow.com/q/403967) which you can then do `document.currentScript.getAttribute('src')` – Meghan Apr 27 '18 at 18:40
  • document.currentScript is great, but we have to support older browsers and IE still. Ugh – Ian Vink Apr 29 '18 at 16:44