Vyacheslav
Vyacheslav

Reputation: 1256

Figuring out the base URL where JS script was loaded from within a script

Assume that I have a JS script included into my HTML page http://app.example.com:

<script src="http://app.foo.com/script.js"></script>

or

<script src="http://app.bar.com/script.js"></script>

which is the same version of JS, but served from different domains. Actually it's the same script that wants to know where it was loaded from.

So basically I want script.js having the code:

// 'app.foo.com' or 'app.bar.com' returned depending where it was loaded from
let baseUrl = somehowGetTheBaseUrlWhereImHostedAt();

P.S. Actually the problem I'm trying to solve is that the JS script would load (insert into DOM) an iframe from app.foo.com/iframe.html if it comes from app.foo.com or app.bar.com/iframe.html if it comes from app.bar.com

Upvotes: 0

Views: 622

Answers (1)

Olian04
Olian04

Reputation: 6872

iframe.html and script.js are unique across all enviroments

Assuming that the script.js file name is pre-determined and unique, we can search for a script tag that imports the given script. Then fetch the full source url from the script tag.

Note: In the example below I am using jquery simply because its available in the SO sandbox.

const fileName = 'jquery.min.js';

// src$="foo" is equivalent to "where the value of the src field ends with 'foo' "
const $script = document.querySelector(`script[src$="${fileName}"]`);
const scriptSrc = $script.src;

console.log(scriptSrc);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Related Questions