How to make javascript variables accessible from any file on the client side?

Hello everyone, I am trying to make variable alias (from background.js) accessible from another javascript file.

I have already tried these methods:
Exporting the variable using export {alias} and then importing it as import {alias} from "js/background.js". This didn’t work, because apparently I can only import from a module.
Placing background.js script tag above the other script tags. When I tried to use alias I got a alias is not defined error.

Thoughts or tips?
Here is the project link: glitch.com/edit/#!/folded-paperjs-test

You can use an object called globalThis. It allows you to set any property and make it available across your entire window.

// test1.js
globalThis.myProperty = "hello world";
// test2.js
console.log(globalThis.myProperty)
// -> "hello world"
2 Likes

You could try localStorage like:

file 1:

var variable = "hello world!";
localStorage.setItem('name', variable)

file 2:

var variable = localStorage.getItem('name')

That’s utterly bad practice unless you need to store session information. Using window or globalThis is definitely a best practice.

2 Likes

wait, both of the files are included in the same html page?

if so, i agree, window or globalthis is better.

otherwise, localstorage might be the only option

Firstly, to answer your question:

Yes, both of the files are in the same window context. Although he’s using ES6 import/export. Or otherwise known as ECMAScript Modules.

Secondly, if you only need to store something short term (or something that doesn’t need to be saved when the client closes the tab) I recommend using sessionStorage opposed of localStorage.

2 Likes

Why is this?

you can make your script a module by putting type=“module”, however this gets annoying because it hides the variables making debugging harder unless you do window.variaible = “smthing”.

globalThis is defined, ignore the stupid linter. That linter has been annoying me since the start of glitch. Don’t worry about it, globalThis is definitely defined :slight_smile:

4 Likes


Why do I get this then :sweat_smile:
note: I tried putting the globalThis.myProperty inside the window.onload function, but it still spits out undefined…

Some more tests I guess:


Basically globalThis and window exist, but not global, but globalThis.myProperty is undefined.

Finally I fixed it - the file with myProperty had an error in it stopping myProperty from entering the global environ.

1 Like