简体   繁体   中英

global variables for different javascript file

I have a web app, which has 2 html pages(html1,html2 related to javascript file js1.js,js2.js) When I click a button on html1, it will navigate to html2. I know there is the way transfer the parameter using url from html1/js1/js to html2/js2.js.

Is there a mechanism that set up variables both j1.js j2.js can access?(likes global variable in c)

Welcome any comment?

This is not directly possible as each page loads with its own window object namespace.

ie A global variable in js1.js (used in page1.html) is actually a member of the window object in page1. Similarly a global variable in page2.html is a member of that page's window object. The 2 window objects are totally different in the sense there is no site wide window or site object that can store global variable for use throughout a site

You can however use window.localStorage to share variables/values across pages in your site.

Example :

Setting value:

window.localStorage.setItem('myglobal', "hello");

Getting value:

var myglobal = window.localStorage.getItem('myglobal');

Variables and values can be passed through pages via querystring. Have a look at this SO article .

If you strictly need to create a Javascript global variable, then you have to include a common snippet in both pages:

var myGlobalVar;

But this only represent a storage accessible by both scripts. You have to set its value anyway.

A hackish solution is to store it into the window.name field. This is shared in the same window/tab of the browser. I personally don't like it. That variable isn't meant to be used this way.

There are libraries to persist state: http://pablotron.org/?cid=1557

Or, you could write your own code to store the variable in session (requires server-side programming), in HTML5 storage, in cookies, etc.

You can either parse window.location.href to extract the parameters, set cookies in one page and retrieve them in the other ( example here ) which also requires parsing or use a server-side solution.

Most probably if you look for in interwebs you can find parsers for URLs and Cookies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM