[英]How to store an object that is retrievable from the client-side in Javascript
[英]Store an Object in client-side and use in new tabs
函數對象不可序列化或結構化克隆。 為了從一個選項卡傳遞到另一個選項卡,對象必須可序列化和反序列化。 從本質上講,這意味着對象的屬性必須能夠轉換為可傳輸的格式,然后又可以轉換回對象。
有簡單的方法來解決您的問題。 這是一個。 在可序列化的對象中捕獲不可序列化對象的所有重要屬性。 然后傳遞可序列化的對象。 然后反序列化。
// file.js (include this on both tabs)
function MyObject() {
this.foo;
this.bar;
}
MyObject.prototype.asdf = function(){};
上面假設我們是您要從一個選項卡轉移到另一個選項卡的對象,但是不能,因為它是一個功能對象。 首先,創建一些輔助函數。
// Create and return a serialized state
MyObject.prototype.serialize = function() {
// Create a simple object of only important state properties
var simpleObject = {};
simpleObject.foo = this.foo;
simpleObject.bar = this.bar;
return simpleObject;
};
// Assign property values to this object from simple object
MyObject.prototype.deserialize = function(simpleObject) {
this.foo = simpleObject.foo;
this.bar = simpleObject.bar;
};
現在,在發送消息時使用這些幫助器。 我將在這里使用一些偽代碼。
// Send the object from one tab to others
function sendMessageHelper() {
// We don't actually send the object, we send its serial form
var myObject = new MyObject();
var transferable = myObject.serialize();
window.postMessage(transferable);
}
// Get the object from the message
function onMessageHandler(message) {
var data = message.data;
// Recreate the state of the object by deserializing
var myObject = new MyObject();
myObject.deserialize(data);
}
最后,確保在兩個頁面(兩個選項卡)中都包含定義對象的js文件。
您可以將函數存儲在JSON對象中。 請遵循此。
在頁面上設置Cookie
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var JSONOBJ={};
var yourfunction=function(){ console.log("hi i am function") }
JSONOBJ["customFunction"]="var customFunction="+yourfunction;
setCookie("CookieWithfunction",JSON.stringify(JSONOBJ),5);
在另一頁上獲取Cookie
var MyJSONOBJ=JSON.parse(getCookie("Myobj"))
eval(MyJSONOBJ.customFunction);
//Call that function
customFunction();
希望這個能對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.