Pass variables between different .js files; one inside the frame

I have a 2.js file in an html document, for example:

<script type="text/javascript" src="js/1.js"></script> <script type="text/javascript" src="js/2.js"></script> 

This document also has an iframe. The iframe also has 2.js:

  <script type="text/javascript" src="js/2.js"></script> <script type="text/javascript" src="js/3.js"></script> 

So 2.js is in both docs. My plan was to put them together. I cannot put 3.js in both documents because it will ruin the material.

1.js got the variable. I want to use this variable in 3.js. But I can’t figure out how to pass a variable from 1.js to 3.js. Is it possible?

* Variable declared in 1.js.

+6
source share
4 answers

You cannot "pass" variables through file links. You will need to add code to transfer data from the parent frame to the iframe.

If the variable is global, it

 //from the iframe var theVariable = window.parent.yourVaraibleName; //from the parent var theVariable = document.getElementById("iframeId").contentWindow.yourVaraibleName; 
+11
source

Why not use jQuery cookies to pass variables? Even inside multiple pages. After passing the variable, you can destroy the cookie.

+3
source

You cannot transfer variables from one js file to another. Javascript stateless variables, so they will not be saved. If you use .Net, you can use session variables to solve this problem. If you use MVC, you can switch to viewbag or viewdata. If it then needs to declare some variable on the home page, then assign a value to be passed to the variable on the home page, and then call the function in 3.js by passing this parameter.

+2
source

jus create a global variable, do not use the var keyword

 myGlobal = "probably not a good idea but still"; 
+1
source

Source: https://habr.com/ru/post/947566/


All Articles