使用javascript跨域localstorage [英] cross domain localstorage with javascript

查看:1014
本文介绍了使用javascript跨域localstorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个javascript api.js,它托管在域api.abc.com上。它管理本地存储。

We have a javascript api.js which is hosted on domain api.abc.com. It manages the local storage.

我们在我们的网站abc.com和login.abc.com中包含此javascript作为跨域js,如

We included this javascript in our websites at abc.com and login.abc.com as a cross domain js like

<script src="http://api.abc.com/api.js">

我知道localstoarge是基于每个域的。但是,由于api.js是从api.abc.com加载的,我预计它将从这两个域访问api.abc.com的本地存储。不幸的是,似乎并非如此。当api.js在一个域的localstoarge中存储一个值时,从其他域加载时无法访问它。

I understand that localstoarge is per domain basis. However since api.js is loaded from api.abc.com, I expected that it will have access to local storage of api.abc.com from both the domains. Unfortunately, it doesn't seem to be the case. When api.js stores a value in localstoarge from one domain, it's not accessible to it when loaded from other domain.

任何想法?

推荐答案

如何使用跨域postmessage和iframes?

How about using cross domain postmessage and iframes?

因此,在您的错误域名页面上,您会添加一个iframe,用于回复包含Cookie数据的邮件。

So on your wrong-domain-page you include an iframe that posts messages with the cookie data back.

以下是跨域邮寄消息的一个可靠示例:
http: //blog.teamtreehouse.com/cross-domain-messaging-with-postmessage

Here is a solid example of cross domain postmessages: http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage

实例:
http://codepen.io/anon/pen/EVBGyz //分叉发送者代码,改变了t::):

live example: http://codepen.io/anon/pen/EVBGyz //forked sender code with a tiiiiiny change :) :

window.onload = function() {
    // Get the window displayed in the iframe.
    var receiver = document.getElementById('receiver').contentWindow;

    // Get a reference to the 'Send Message' button.
    var btn = document.getElementById('send');

    // A function to handle sending messages.
    function sendMessage(e) {
        // Prevent any default browser behaviour.
        e.preventDefault();

        // Send a message with the text 'Hello Treehouse!' to the new window.
        receiver.postMessage('cookie data!', 'http://wrong-domain.com');
    }

    // Add an event listener that will execute the sendMessage() function
    // when the send button is clicked.
    btn.addEventListener('click', sendMessage);
}

收货人代码:

Receiver code:

window.onload=function(){
    var messageEle=document.getElementById('message');
    function receiveMessage(e){
        if(e.origin!=="http://correct-domain.com")
        return;
        messageEle.innerHTML="Message Received: "+e.data;
    }
    window.addEventListener('message',receiveMessage);
}

这篇关于使用javascript跨域localstorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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