Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Using the cross-domain messaging API

From: HTML5 Power Workshop

Video: Using the cross-domain messaging API

In this lesson, we're going to look at the API for performing cross to main messaging in HTML5. Whereby, you can send messages from one window to another, even if they've been downloaded from different domains. So, we have two files in the example. The first file is main window the HTML, which allows me to deposit money and withdraw money from bank account. So let me deposit 1000 pounds. And then, when I click the new Window button, it'll open up several windows. And each window contains a web page from a different domain, so the main page is in my domain 1.

Using the cross-domain messaging API

In this lesson, we're going to look at the API for performing cross to main messaging in HTML5. Whereby, you can send messages from one window to another, even if they've been downloaded from different domains. So, we have two files in the example. The first file is main window the HTML, which allows me to deposit money and withdraw money from bank account. So let me deposit 1000 pounds. And then, when I click the new Window button, it'll open up several windows. And each window contains a web page from a different domain, so the main page is in my domain 1.

And the child windows come from my domain 2, okay? So, when I click the Broadcast button here, it'll broadcast a message from the main window to the child windows. And the child windows handle that message and update the balance that each window's displaying. So a 1000 pounds is now displayed on each window. We can also post messages back the other way, if I click the Levy Fee button. Then it will post a message back to the main window and the main window will accept the message and take 10 pounds off the balance and tell each window what the new balance is. So, let's take a look at these two files in the editor main window and child window through HTML.

I have the Editor open here ready. You need to make sure, if you want to run this example, to copy these two files into different servers on your machine. To illustrate properly effect of cross domain messaging. So main window, the HTML first of all. I'll take you to the bottom of the file, just to show you what the page actually looks like. So, we have a text box where we can enter the amount to deposit or withdraw. And then two buttons to actually do the deposit or withdraw.

And then another two buttons, to open up any number of new windows. And to broadcast a message to each one. Let me take you to the top of the page now, and show you some global script variables. we store the balance in a global variable at zero, initially. This is the URL of the document that I'm going to open up in each page. And as you can see is in a different domain, my domain 2 compared to the main window. And also I keeping away of all the code windows that I've opened, so that I can broadcast the message each of them when I click the Broadcast button.

I've also got some variables here just to do some maths just to layout the child windows nicely. Now the first three functions here are relatively straightforward. I'll just scroll down a little bit so you can see what they look like. So the deposit function just simply gets the amount from the textbox, adds that amount into the balance. And then pops up a message box to say that's been deposited into the account. And the withdraw function does a similar kind of thing. It withdraws the amount from the balance. And then when I click New Window, it does some maths first of all, to figure out where the new child window should go.

And then of course, the window open function. To open the window, remember the child window URL was my domain to childwindow.html. So, that's the window that's going to be open and the maths here specify where the window is going to be located. And then we store that window also, in the array so that I can broadcast the message to each one later on. And that happens when I lcick the Broadcast button on the main page. And this is how that function works. I iterate through all my child windows, and I use the post message function to post a message to each window.

So you take a window object, and you call the post message function. The post message function takes two parameters. The first parameter is whatever data you want to pass in to the other window. So, in this case, it's just a simple number, the balance. But it could be a complex JSON object if you wanted it to be. The second parameter specifies, what do you expect from the child window? Where do you expect the child window to have come from? Now, a star means I don't actually care which domain the child window was downloaded from. If you want to, you can stipulate that the child window must have been downloaded from this domain.

If you say slash, it means the child window must have been downloaded from the same domain as the main window, okay? So, this post message function would post this data to the child window. So, what we need to do now is to see how the child window handles that message. So, let's go into the child window through HTML, and just scroll down a little bit, just to show the user interface first. It has a div but the current balance can be displayed so initially the balance field stays unspecified.

This is the important point, this is how you can handle incoming messages that are been posted to you. On your window object, I have added a event listener, so that when the message event comes in, it calls my event time to function here, on message. So in the main window, posts a message. This function will be invoked, and inside your handler, you always get the opportunity to check the origin of the sender.

And you probably want to do that in most cases. The on message handler, has an event prompter and the event prompter has an origin property. This is the origin and that includes the schemer and the domain name, plus optionally a port number. And the origin you can test it either against a single domain if you want to. Or maybe you have, an array or collection of domains that you're prepared to accept messages from. So it's always up to you as the receiver to decide whether you want to accept or reject the message that's been sent to you.

You can never be forced to do anything when you receive a message. So, in this example, if the origin of the sender was my domain 1, then we get the data that's been sent over. Remember, that was just the new balance and we display that new balance on the screen. So, it puts the new balance into this span down here. If the origin was anything other than my domain 1. Then we pop up a message box to reject the message, and tell the user that it's being rejected. So, that's how you can send and receive data from the main window to the channel window.

You can also post messages in the reverse direction. And that's what happened when I clicked on the child window, the Levy Fee button. It sends a message back to the original page. So Window Opener, is the page that opened this trial window. And then posting the message back in the reverse direction. To say, I want to take off 10 pounds from the balance please and I'm not really fussed about where the main window came from. Start again means I don't really care what is the origin of the reciever from the sender's point of view. So, when the child window posts a message to the main window. The main window handles it in the same fashion you have to in the main window handle the message event.

And I've done that here down on line 67. On the main window, we also handle the message event. And the main window has its own on message function, and that's what we have here. So on the main window, the on message function checks the origin of the incoming data. Who sent the data? If the data came from the child window domain, my domain 2, then we accept the message and we just tell the user we've accepted this data from the child window.

And we take the data, which is 10 pounds, subtract that from the balance, and then do a broadcast again. And the broadcast function will send messages to all the child windows again with a new balance. So that concludes the lesson. We've seen how you can communicate the message coming from different windows coming from different domains by using the Post Message function. And then when you receive a message from another window, you handle it by the message event. And in the message event, you have an origin property that you can check to see whether or not you want to accept the message that's been posted to you by the other window.

Show transcript

This video is part of

Image for HTML5 Power Workshop
HTML5 Power Workshop

22 video lessons · 4047 viewers

Andy Olsen
Author

 

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now "Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed HTML5 Power Workshop.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.