cross domain localstorage with javascript

后端 未结 4 1713
挽巷
挽巷 2020-12-09 03:11

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

We included this javascript in our websites at abc.com and login.abc

4条回答
  •  半阙折子戏
    2020-12-09 03:34

    How about using cross domain postmessage and iframes?

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

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

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

提交回复
热议问题