DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Having Fun with the Lightning Design System for React
  • An Introduction to Type Safety in JavaScript With Prisma
  • Building AMQP-Based Messaging Framework on MongoDB
  • The Complete Tutorial on the Top 5 Ways to Query Your Relational Database in JavaScript - Part 2

Trending

  • Distributed Consensus: Paxos vs. Raft and Modern Implementations
  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  • Implementing Explainable AI in CRM Using Stream Processing
  • AI Agents: A New Era for Integration Professionals
  1. DZone
  2. Data Engineering
  3. Data
  4. Cross-Domain Data Sharing in JavaScript

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.

By 
Sibeesh Venu user avatar
Sibeesh Venu
·
Jan. 25, 16 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
21.2K Views

Join the DZone community and get the full member experience.

Join For Free

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!

clone source code

  • sender application
  • receiver application

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 this? did you find this post useful? i hope you liked this article. please share your valuable suggestions and feedback with me.

    Data (computing) application Data sharing JavaScript

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

    Opinions expressed by DZone contributors are their own.

    Related

    • Having Fun with the Lightning Design System for React
    • An Introduction to Type Safety in JavaScript With Prisma
    • Building AMQP-Based Messaging Framework on MongoDB
    • The Complete Tutorial on the Top 5 Ways to Query Your Relational Database in JavaScript - Part 2

    Partner Resources

    ×

    Comments
    Oops! Something Went Wrong

    The likes didn't load as expected. Please refresh the page and try again.

    ABOUT US

    • About DZone
    • Support and feedback
    • Community research
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

    • Article Submission Guidelines
    • Become a Contributor
    • Core Program
    • Visit the Writers' Zone

    LEGAL

    • Terms of Service
    • Privacy Policy

    CONTACT US

    • 3343 Perimeter Hill Drive
    • Suite 100
    • Nashville, TN 37211
    • support@dzone.com

    Let's be friends:

    Likes
    There are no likes...yet! 👀
    Be the first to like this post!
    It looks like you're not logged in.
    Sign in to see who liked this post!