0

can anyone help me to pass variables from one .js file to another one, the two .js are instantiated in the same html as following:

<script src="file_1.js"></script>

<script src="file_2.js"></script>

the content of "file_1.js" is like this:

var paragraph = readFile('file_to_read.tcl'); 

so what i need, is to use the "paragraph " variable in side the "file_2.js script

Great thanks in advance

Elhabib
  • 39
  • 3

1 Answers1

0

You can save them locally like this:
file_1.js:

window.paragraph = readFile('file_to_read.tcl'); 

file_2.js:

setTimeout(function(){ //a small timeout to let the variable be declared...
  alert(window.paragraph);
}, 100);

Codepen

Yuval.R
  • 707
  • 1
  • 10
  • Many thanks Yuval, do I need a specific environment to use this ? jut tested it in rhino & got this issue : "js: uncaught JavaScript runtime exception: ReferenceError: "localStorage" is not defined." – Elhabib Nov 02 '20 at 13:00
  • This is weird... I'll take a look at this once I'm home. – Yuval.R Nov 03 '20 at 13:54
  • Idk if this works but please try. https://stackoverflow.com/a/62113977 – Qrazier Nov 03 '20 at 14:13
  • I have test it in [codepen](https://codepen.io/Yuvix/project/editor/AnGkRz) and it works just fine, perhaps the problem is with Rhino. – Yuval.R Nov 03 '20 at 16:16
  • OK, I found another working solution, try it (I have also updated the codepen). – Yuval.R Nov 03 '20 at 16:45
  • i see it works, Many thanks, but this one :" window.paragraph = 'testttt'; " should be replaced by " window.paragraph = 'readFile('file_to_read.tcl') '; " to read the file to the variable named "paragraph" – Elhabib Nov 04 '20 at 08:19
  • I tested it: file_1.js: setTimeout(function(){ window.paragraph = readFile('file_to_read.tcl'); localStorage.setItem("paragraph", paragraph); }, 100); and got this error: "TypeError: readFile is not a function" – Elhabib Nov 04 '20 at 08:34
  • This is already a problem with your code, this is what you wrote. – Yuval.R Nov 04 '20 at 10:22