使用javascript跨域本地存储

新手上路,请多包涵

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

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

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

我知道 localstoarge 是基于域的。然而,由于 api.js 是从 api.abc.com 加载的,我希望它可以从两个域访问 api.abc.com 的本地存储。不幸的是,情况似乎并非如此。当 api.js 从一个域将值存储在 localstoarge 中时,从其他域加载时它无法访问它。

任何想法?

原文由 mesibo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 487
1 个回答

使用跨域邮寄消息和 iframe 怎么样?

因此,在您的错误域页面上,您包含一个 iframe,该 iframe 会发布带有 cookie 数据的消息。

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

活生生的例子: http ://codepen.io/anon/pen/EVBGyz //forked sender code with a tiiiiiiny 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);
}

收件人代码:

 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);
}

原文由 25r43q 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题