是否有任何解决方法可以在http和https上使用html5 localstorage? [英] Is there any workaround to make use of html5 localstorage on both http and https?

查看:672
本文介绍了是否有任何解决方法可以在http和https上使用html5 localstorage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要存储一些数据客户端,而这些数据太大而无法将其存储在cookie中。 LocalStorage似乎是这样做的完美方式,但事实是,我将使用它的网站有一些部分适用于https和其他只有http和本地存储无法访问您使用http设置的https数据这似乎不再是一个可行的解决方案。



任何想法,如果有任何解决方案呢?还有其他选择吗?

解决方案

将所有数据存储在一个域中,例如 https://my.domain.org/




  • https 协议,只需使用 localStorage.setItem('key','value')来保存数据。 b $ b
  • http 协议上,嵌入 https 框架,并使用 postMessage 来保存数据:



演示 http://jsfiddle.net/gK7ce/4/ (辅助页面位于 http ://jsfiddle.net/gK7ce/3/ )。

  // https://我的脚本.domain.org / postMessage 
window.addEventListener('message',function(event){
//域限制(不会将变量泄漏到任何页面中)
if(event。 origin =='http://my.domain.org'||
event.origin =='https://my.domain.org'){
var data = JSON.parse(event.data);
if('setItem'in data){
localStorage.setItem(data.setItem,data.value);
} else if('getItem'in data){
var gotItem = localStorage.getItem(data.getItem);
//见下面
event.source.postMessage(
'#localStorage#'+ data.identifier +
(gotItem === null?'null#':'# '+ gotItem),
event.origin
);
} else if('removeItem'in data){
localStorage.removeItem(data.removeItem);
}
}
},false);

在http页面上,框架可以嵌入如下( replace https://my.mydomain.com 与实际的URL 。请注意,您可以简单地获取对框架的引用,并使用 src 属性):

 < iframe name =myPostMessagesrc =https:/ /my.domain.org/postMessagestyle =display:none;>< / iframe> 
//示例:设置数据
函数LSsetItem(键,值){
var obj = {
setItem:key,
value:value
};
frames ['myPostMessage']。postMessage(JSON.stringify(obj),'https://my.domain.com');
}
LSsetItem('key','value');

请注意,该方法是异步的,因为 postMessage 。必须以不同的方式实现 getItem 方法:

  var回调= {}; 
window.addEventListener('message',function(event){
if(event.source === frames ['myPostMessage']){
var data = / ^#localStorage#( (数据){
if(callbacks [data [1]);(b)如果(数据){
if(callbacks [data [1] ]){
// null和null由我们的模式
回调[data [1]](data [2] ==='null'?null:data [3])区分;
}
删除回调[data [1]];
}
}
},false);
函数LSgetItem(key,callback){
var identifier = new Date()。getTime();
var obj = {
标识符:标识符,
getItem:键
};
回调[标识符] =回调;
frames ['myPostMessage']。postMessage(JSON.stringify(obj),'https://my.domain.com');
}
//用法:
LSgetItem('key',function(value){
console.log('Value:'+ value);
}) ;

请注意,每个回调都存储在一个散列中。每条消息还包含一个标识符,以便接收该消息的窗口调用正确的对应回调。



为了完整起见,这里是 LSremoveItem 方法:

$ p $ 函数LSremoveItem(key){
var obj = {
removeItem :key
};
frames ['myPostMessage']。postMessage(JSON.stringify(obj),'https://my.domain.com');
}


I need to store some data client side and this data is too large to store it in a cookie. LocalStorage seemed like the perfect way of doing this but the thing is that the website that i will be using this has some parts that work on https and others with just http and as local storage can't access data from https that you set with http this doesn't seem like a viable solution anymore.

Any idea if there is any solution to this? Any other alternatives?

解决方案

Store all data on one domain, e.g. https://my.domain.org/.

  • On https protocols, simply use localStorage.setItem('key', 'value') to save the data.
  • On http protocols, embed a https frame, and use postMessage to save the data:

Demo: http://jsfiddle.net/gK7ce/4/ (with the helper page being located at http://jsfiddle.net/gK7ce/3/).

// Script at https://my.domain.org/postMessage
window.addEventListener('message', function(event) {
    // Domain restriction (to not leak variables to any page..)
    if (event.origin == 'http://my.domain.org' ||
        event.origin == 'https://my.domain.org') {
        var data = JSON.parse(event.data);
        if ('setItem' in data) {
            localStorage.setItem(data.setItem, data.value);
        } else if ('getItem' in data) {
            var gotItem = localStorage.getItem(data.getItem);
            // See below
            event.source.postMessage(
                '#localStorage#' + data.identifier + 
                (gotItem === null ? 'null#' : '#' + gotItem),
                event.origin
            );
        } else if ('removeItem' in data) {
            localStorage.removeItem(data.removeItem);
        }
    }
}, false);

On the http(s) page, the frame can be embedded as follows (replace https://my.mydomain.com with the actual URL. Note that you can simply get a reference to the frame, and use the src attribute):

<iframe name="myPostMessage" src="https://my.domain.org/postMessage" style="display:none;"></iframe>
// Example: Set the data
function LSsetItem(key, value) {
    var obj = {
        setItem: key,
        value: value
    };
    frames['myPostMessage'].postMessage(JSON.stringify(obj), 'https://my.domain.com');
}
LSsetItem('key', 'value');

Note that the method is asynchronous, because of postMessage. An implementation of the getItem method has to be implemented differently:

var callbacks = {};
window.addEventListener('message', function(event) {
    if (event.source === frames['myPostMessage']) {
        var data = /^#localStorage#(\d+)(null)?#([\S\s]*)/.exec(event.data);
        if (data) {
            if (callbacks[data[1]]) {
                // null and "null" are distinguished by our pattern
                callbacks[data[1]](data[2] === 'null' ? null : data[3]);
            }
            delete callbacks[data[1]];
        }
    }
}, false);
function LSgetItem(key, callback) {
    var identifier = new Date().getTime();
    var obj = {
        identifier: identifier,
        getItem: key
    };
    callbacks[identifier] = callback;
    frames['myPostMessage'].postMessage(JSON.stringify(obj), 'https://my.domain.com');
}
// Usage:
LSgetItem('key', function(value) {
    console.log('Value: ' + value);
});

Note that each callback is stored in a hash. Each message also contains an identifier, so that the window which receives the message calls the correct corresponding callback.

For completeness, here's the LSremoveItem method:

function LSremoveItem(key) {
    var obj = {
        removeItem: key
    };
    frames['myPostMessage'].postMessage(JSON.stringify(obj), 'https://my.domain.com');
}

这篇关于是否有任何解决方法可以在http和https上使用html5 localstorage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆