A super method for multiple jsp pages to share an js object

  • 2020-12-20 03:43:05
  • OfStack

Today, I encountered a problem in a project where two js pages would share one on an js object. js global variables and static variables do not work, other helpless suffering smallholders do not have to force. And LZ does not want to use cookie to store, 1 is not safe, 2 people like. Finally, I found a super way to solve this problem, which is to use window.top ['_CACHE'] to store this variable, so as to realize the direct object sharing of different Jsp pages.


var share = { 

/** 
*  Data sharing interfaces across frameworks  
* @param {String}  The name of the stored data  
* @param {Any}  Any data to be stored ( Returns the data queried without this item ) 
*/ 
data: function (name, value) { 
var top = window.top, 
cache = top['_CACHE'] || {}; 
top['_CACHE'] = cache; 

return value !== undefined ? cache[name] = value : cache[name]; 
}, 

/** 
*  Data sharing delete interface  
* @param {String}  The name of the deleted data  
*/ 
removeData: function (name) { 
var cache = window.top['_CACHE']; 
if (cache && cache[name]) delete cache[name]; 
} 

};


Paste the LZ code below:

1 jsp page of LZ is A.jsp, click 1 button in A.jsp to open another B.jsp page. LZ's thinking is as follows:

In the event that ES29en. jsp opens ES31en. jsp, write the following code:


window.top['_CACHE'] = chatFrdList; 
window.top['_CACHE'][frdUserId] = frdUserId;

Where, chatFrdList is defined as var chatFrdList = new Object();

frdUserId is id for 1 user.

Then, in an event of ES48en.jsp, you can do the following:


<pre name="code" class="javascript" style="margin-top:0px; margin-bottom:0px; padding:0px; font-family:'courier new',courier,monospace">var e = document.getElementsByName("chatWindow");</pre><pre name="code" class="javascript" style="margin-top:0px; margin-bottom:0px; padding:0px; font-family:'courier new',courier,monospace">var keyId = e[0].id; 
delete window.top['_CACHE'][keyId];//  When you close the chat window with the friend, remove it from the chat table </pre>


LZ can then operate on window.top ['_CACHE'] in other events of ES56en.jsp, making it possible to share js objects directly across multiple JSP pages.


Related articles: