Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Cross-Domain Data Sharing in JavaScript

DZone's Guide to

Cross-Domain Data Sharing in JavaScript

In this post, we will see how we can send data to another domain from our application using the postMessage method. Read on to learn more.

· Web Dev Zone
Free Resource

Prove impact and reduce risk when rolling out new features. Optimizely Full Stack helps you experiment in any application.

In this post, we will see how we can send data to another domain from our application. You can simply call it cross domain data sharing. In a few cases we may need to send some data which is needed for our other domain or application to work as expected. I had some of these cases in my programming life. I have done this requirement with the help of the postMessage method. The window.postMessage method helps us to enables cross-origin communication. I hope you enjoy this!

Download Source Code

  • CrossDomainDataSharing.rar
  • Receiver.rar
  • Background

    I was forced to maintain some cookies in my second application every time. I wanted to set that the same from my first application, too. So, I implemented this with the help of window.postMessage. For the demo purpose, I am creating two applications here.

  • CrossDomainDataSharing
  • Receiver
  • Using the Code

    First, we will concentrate on the CrossDomainDataSharing application in which we are sending our data to the Receiver application.

    To start with you need to add a jQuery reference to your page. And, to make this application trendy, I have added Smart Alert to our application. You can see the necessary references and styles below.

    <script src="Scripts/jquery-2.2.0.min.js"></script>
        <script src="js/alert.min.js"></script>
        <link href="css/alert.min.css" rel="stylesheet" />
        <link href="themes/dark/theme.css" rel="stylesheet" />

    Next thing is the “Calling Window On Load” Function.

     window.onload = function () {
                document.getElementById('btnSend').addEventListener('click', sendData);
            };

    Here, we are just adding a click event to the button with id btnSend. Before going to add the event, please make sure that you have created a button.

     <button id="btnSend">Send Feedback</button>

    The next thing is to create an iframe and load our second application link to that by giving src value.

     <iframe id="ifrLoad" src="http://localhost:55592/Receiver/Cross-Domain-Data-Sharing-Receiver.html" style="display: none;">
            <p>Oops!. Your browser does not support iframes.</p>
        </iframe>

    Have you noticed that we have called a function called sendData. Let us see what that function does.

    function sendData(e) {
                try {
                    $.alert.open('prompt', 'Please send your feedback!.', function (button, value) {
                        if (button == 'ok') {
                            e.preventDefault();;
                            var myIfr = window.frames['ifrLoad'].contentWindow;
                            myIfr.postMessage(value, 'http://localhost:55592/Receiver/Cross-Domain-Data-Sharing-Receiver.html')
                            $.alert.open('Thank you so much for your feedback.' || 'No value has been entered');
                        }
                    });
    
                } catch (e) {
                    console.log('Error: ' + e.message);
                }
            }

    We are creating a smart alert first if the user says "Ok", we will just pass the given feedback to our second application with the help of the postMessage method. The implementation is pretty simple. Isn’t it?

    You can style the button you have created as follows.

    <style>
            #btnSend {
                margin-left: 11px;
                border: solid 1px #000;
                padding: 9px 22px 7px;
                min-width: 32px;
                font-weight: bold;
                line-height: 13px;
                color: #fff;
                text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
                background-color: #232323;
                background-image: linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                background-image: -webkit-linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                background-image: -moz-linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                background-image: -o-linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                background-image: -ms-linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                -pie-background: linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                border-radius: 3px;
                -webkit-border-radius: 3px;
                -moz-border-radius: 3px;
                -ms-border-radius: 3px;
                box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                -webkit-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                -moz-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                -ms-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                -o-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
            }
    
                #btnSend:hover {
                    background-color: #404040;
                    background-image: linear-gradient(#515151 1%, #2e2e2e);
                    background-image: -webkit-linear-gradient(#515151 1%, #2e2e2e);
                    background-image: -moz-linear-gradient(#515151 1%, #2e2e2e);
                    background-image: -o-linear-gradient(#515151 1%, #2e2e2e);
                    background-image: -ms-linear-gradient(#515151 1%, #2e2e2e);
                    -pie-background: linear-gradient(#515151 1%, #2e2e2e);
                    box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                    -webkit-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                    -moz-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                    -ms-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                    -o-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                }
        </style>

    Now that is all for the sending part, please see the complete code for our first application here.

    <!DOCTYPE html>
    <html>
    <head>
        <title>Cross Domain Data Sharing Demo - Sibeesh Passion</title>
        <script src="Scripts/jquery-2.2.0.min.js"></script>
        <script src="js/alert.min.js"></script>
        <link href="css/alert.min.css" rel="stylesheet" />
        <link href="themes/dark/theme.css" rel="stylesheet" />
        <style>
            #btnSend {
                margin-left: 11px;
                border: solid 1px #000;
                padding: 9px 22px 7px;
                min-width: 32px;
                font-weight: bold;
                line-height: 13px;
                color: #fff;
                text-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
                background-color: #232323;
                background-image: linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                background-image: -webkit-linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                background-image: -moz-linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                background-image: -o-linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                background-image: -ms-linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                -pie-background: linear-gradient(#2b2b2b 1%, #1d1d1d 99%);
                border-radius: 3px;
                -webkit-border-radius: 3px;
                -moz-border-radius: 3px;
                -ms-border-radius: 3px;
                box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                -webkit-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                -moz-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                -ms-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                -o-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
            }
    
                #btnSend:hover {
                    background-color: #404040;
                    background-image: linear-gradient(#515151 1%, #2e2e2e);
                    background-image: -webkit-linear-gradient(#515151 1%, #2e2e2e);
                    background-image: -moz-linear-gradient(#515151 1%, #2e2e2e);
                    background-image: -o-linear-gradient(#515151 1%, #2e2e2e);
                    background-image: -ms-linear-gradient(#515151 1%, #2e2e2e);
                    -pie-background: linear-gradient(#515151 1%, #2e2e2e);
                    box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                    -webkit-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                    -moz-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                    -ms-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                    -o-box-shadow: 0 1px rgba(2, 3, 3, 0.5), 0 1px rgba(255, 255, 255, 0.07) inset, 0 0 0 1px rgba(255, 255, 255, 0.06) inset;
                }
        </style>
        <script>
            window.onload = function () {
                document.getElementById('btnSend').addEventListener('click', sendData);
            };
            function sendData(e) {
                try {
                    $.alert.open('prompt', 'Please send your feedback!.', function (button, value) {
                        if (button == 'ok') {
                            e.preventDefault();;
                            var myIfr = window.frames['ifrLoad'].contentWindow;
                            myIfr.postMessage(value, 'http://localhost:55592/Receiver/Cross-Domain-Data-Sharing-Receiver.html')
                            $.alert.open('Thank you so much for your feedback.' || 'No value has been entered');
                        }
                    });
    
                } catch (e) {
                    console.log('Error: ' + e.message);
                }
            }
        </script>
    </head>
    <body>
        <button id="btnSend">Send Feedback</button>
        <iframe id="ifrLoad" src="http://localhost:55592/Receiver/Cross-Domain-Data-Sharing-Receiver.html" style="display: none;">
            <p>Oops!. Your browser does not support iframes.</p>
        </iframe>
    </body>
    </html>

    Now, we will concentrate on our second application "Receiver".

    We will just add a window load function with event listener which accepts the data from our first application. Please see the following code for further clarification.

     $(window).load(function () {
                window.addEventListener('message', addData);
                function addData(e) {
                    document.cookie = "myData=" + e.data;
                };
            });

    Here myData is the cookie name.

    You can see the complete code for our second application here.

    <!DOCTYPE html>
    <html>
    <head>
        <title>Cross Domain Data Sharing Receiver - Sibeesh Passion</title>
        <script src="Scripts/jquery-2.2.0.min.js"></script>
        <script>
            $(window).load(function () {
                window.addEventListener('message', addData);
                function addData(e) {
                    document.cookie = "myData=" + e.data;
                };
            });
        </script>
    </head>
    <body>
    </body>
    </html>

    Now it is time to see our output.

    Output

    While sending the data to our second application.

    Cross_Domain_Data_Sharing_Sender

    Cross_Domain_Data_Sharing_Sender

    Smart_Alert

    Smart_Alert


    While receiving the data in our second application.

    Receiving_data_from_another_domain

    Receiving_data_from_another_domain


    That is all. We did it. Have a happy coding.

    Conclusion

    Did I miss anything that you think is necessary? Have you ever been required to do thist? Did you find this post useful? I hope you liked this article. Please share your valuable suggestions and feedback with me.

    With SDKs for all major client and server side platforms, you can experiment on any platform with Optimizely Full Stack.

    Topics:
    jquery ,javascript ,html

    Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.

    Opinions expressed by DZone contributors are their own.

    {{ parent.title || parent.header.title}}

    {{ parent.tldr }}

    {{ parent.urlSource.name }}