Home > Enterprise >  How to know which file called index.js?
How to know which file called index.js?

Time:03-17

I've three html files a.html,b.html & c.html

All of them call index.js.

Inside index.js, I'm importing a variable from a.js,b.js & c.js. Based on which html file called index.js , I want to use the variable from the corresponding js file inside index.js.

pic

It's not possible for me to remove index.js as it contains logic, which is needed for some other tasks.

Some more clarification:

index.js


if calling_html == a.html:
   import {variable} from a.js
else if calling_html == b.html:
   import {variable} from b.js
else 
   import {variable} from c.js

How to find calling_html?

CodePudding user response:

I'd suggest looking at this post : How to pass parameters to a Script tag?

Basically you pass in a value in the script tag, which tells the index.js script which from which file you are loading it.

And then use

document.currentScript.getAttribute()

Edit : I find it less recommendable, but if you absolutely so wish, you can also use :

the

window.location

attribute

using window.location.href, or window.location.pathname

Alternatively, what is shown here :

https://www.sitepoint.com/get-url-parameters-with-javascript/

by doing something like

const urlParams = new URLSearchParams(window.location.search); const caller = urlParams.get('caller');

And load your a.html page with "[...]a.html?caller=a"

Now with all that said, I'm assuming that you don't want define a global constant with a header script tag in the page before using index.js as in

<head>
    //called before loading any other script
    <script>const caller='a.html';</script>
    // Rest of the header
</head>
// somewhere else
<script src="./index.js" />

and

<head>
    //called before loading any other script
    <script>const caller='b.html';</script>
    // Rest of the header
</head>
// somewhere else
<script src="./index.js" />

CodePudding user response:

Make sure your index.js parsed after a, b ,c js for each page then just const myVariable = a || b || c

  • Related