开发者

How to maintain and access javascript variable which is accesible from all the pages?

开发者 https://www.devze.com 2023-01-31 08:55 出处:网络
I have a temp.js file containing global variable \'num\' which is intially set to 0. It has a function Increment() which increments the num by 1.

I have a temp.js file containing global variable 'num' which is intially set to 0. It has a function Increment() which increments the num by 1.

I have 2 html files Page1.html and Page2.html. Both are referring to temp.js file (). Both th开发者_开发百科e pages are having a button on click of which I call a javascript and navigate to the other page. i.e, on button click from Page1.html I navigate to Page2.html and vice versa.

Before navigating from any page, I call Increment() function. What I see is num is always intialized to 0 and Increment function sets it to 1. What I want is num be set to 0 for the very first time and later increment by 1 anytime I call the function.

Anyway that I can acheive the above. Passing the value using querystring or maintaining masterpage of some kind is ruled out in my scenario.


You can write the cookies. That is the best you can do.


Your best bet would be to write the variable to a cookie. Note that this is one of the easiest spoofable methods that exist, so if the counter is in any way "important" you should refrain to do this.

In this last case your best bet would be to store the counter in a session variable. That would need 1) a server-side language (e.g. PHP, ASP, Perl) 2) an asynchronous call (AJAX) to a page on the server that updates the session.


You could also have a master page, which iframed Page1.html. When you browse to Page2.html in the iframe, the parent page's context will still exist. You can then reference your global counter from the two documents in the frame using parent.counter.

However, using an iframe would add one additional http request on page load, as well as incur additional resources consumed by the browser. It would also complicate your site. A cookie solution would add bytes to every request you issued to the server. Your choice.

0

精彩评论

暂无评论...
验证码 换一张
取 消