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

Registering a listener

From: HTML5: Messaging and Communications in Depth

Video: Registering a listener

The first step to implementing HTML5 messaging is to register a listener. This is done with the addEventListener method of the object you want to listen to. So what I have here is a working copy of listener-one-start.html and working copy of listener-two-start.html. I have named them both -working. And these are in the Chap02 folder of the exercise files, and I've loaded them up on my server so that we can test them there. And the first thing that I need to do is I need to come down here to lines 35 and 36 and make sure that these match.

Registering a listener

The first step to implementing HTML5 messaging is to register a listener. This is done with the addEventListener method of the object you want to listen to. So what I have here is a working copy of listener-one-start.html and working copy of listener-two-start.html. I have named them both -working. And these are in the Chap02 folder of the exercise files, and I've loaded them up on my server so that we can test them there. And the first thing that I need to do is I need to come down here to lines 35 and 36 and make sure that these match.

So I'm in listener-one-working, and so I need the origin for the listener-two, and I need the URL for listener-two. Now the origin is just this. It's the protocol :// and the domain name and a port, if you're using one and probably not--that's very rarely done. The URL, in this case I need to change the word start over here to be working, so that it loads up the right version of the file. And I just pressed Save and you saw a little dialog box come up while it saved.

I'm actually editing directly on the server. My editor will do that over SFTP, and I strongly recommend that you have an editor that does that. I'm using TextWrangler on a Mac here. At home I use BBEdit, which is the pay-for- it version of TextWrangler. TextWrangler is free. And if you're on a PC you can use Notepad++, which has that feature as well. Now if you don't change this, the danger is that you'll load up a different version of the same file and it will look like it's working, but you will make changes to that file and nothing changes on the screen, and you end up pulling your hair out.

So I strongly recommend that you start each one of these lessons by making sure that you have these two things correct in both of the files. So this is in the -one file. And if I bring up the -two file, come down here to line 21, I'll see the same thing. This just has the origin; it doesn't actually need the URL of the -one file. And so it's got the originOne, and you want to make sure that that matches the origin that you're using. So let's just take a quick page-through of these files so that those who are typing along at home can do so.

So that's listener-one-working.html, and this is listener-two-working.html. These of course are copies of the -start files. I strongly recommend you work with copies, that you don't work with the -done files, that you just start with the -start files and work with copies. And that way if you get stuck or lost, you can make a fresh copy and work from there. All right! So now we got our files copied, our files typed in, and we're going to get to work.

The first thing we want to do in implementing a listener is to write the function that's going to handle the message event, and that function is going to be called handleMessage. And it gets an event object as its sole parameter, and the first thing that it does is it tests the origin. The event object has an origin member, so it says if (event.origin == originTwo). And you notice originTwo up here has that string in it, the origin of the -two document.

And I'm just going to go ahead and write the else right now, because this is a condition that we want to be concerned with. If the origin does not match, you want to do something other than actually use that data, and so I'm just going to display an error message. I am going to call my display error function, which you can find down below in the Utilities section. My error message will be informative. You don't necessarily want to do this in production, be informative, you might want to do something even nastier in production. But I'm just going to say, "message from untrusted origin," and I'm going to say what that untrusted origin is.

So we can test it, and we can play around with it, and we can know exactly what's going on. Now the next thing I want to do is I want to test if I have a windowTwo object. If I don't, I'm going to grab it from the source. So I'm going to say, if not windowTwo. And you notice that windowTwo up here is defined as null, and so if it's still null, I'm going to assign it from the event. windowTwo = event.source. So the source member of the event object has that. It's actually a window proxy, but it works just like the window object, and so you don't even need to know that it's not.

Now I'm going to log a message. I have this lovely little log method that displays those log messages on the screen. And I'm going to say message from origin, and I'm going to give the event.origin. You can see what that looks like. And then I'm going to log the data. And that's our handleMessage function. Now all I need to do is register it. And I come down here into init, and you remember that init gets assigned, it gets called, because it's assigned to the onload handler for the whole window.

So once the page has completely loaded, then we call init. So the first thing I'm going to do in init is I'm going to add the eventListener, window.addEventListener, and it's for the message event, and it's going to called the handleMessage function. And then it gets this other parameter, which is false, which has to do with the way that messages propagate in the DOM, and it's always going to be false. So I'll go ahead and I'll save this. I'm just pressing Command+S here on the Mac. And then we can over to the listener-two-working, and we're going to do the same kind of stuff.

I am going to come down here and make sure that our origin is correct there on line 21, and then I'm going to go ahead and create a handleMessage function. And actually, if you want to, because laziness is a virtue, I will just copy and paste this from the other one and just edit it. So our origin is going to be originOne. We don't need to test for windowTwo or even for windowOne, because we're not sending messages back--at least not from this function. And the rest of this is exactly the same.

Then we come down here into the init function and we add our eventListener. And actually, this isn't used yet. We can go ahead and delete that line. So I'm saving the file and we have now registered our listeners. When we run this in the browser, listener-one-working, we see that it's running properly. It's not really sending any messages yet-- we'll get to that in the next movie-- but you can see for now that it's really a straightforward process to register a listener: you just create the message handler and then you pass the function reference to addEventListener.

In the next movie, we'll go ahead and send some messages back and forth.

Show transcript

This video is part of

Image for HTML5: Messaging and Communications in Depth
HTML5: Messaging and Communications in Depth

11 video lessons · 5763 viewers

Bill Weinman
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: Messaging and Communications in Depth.

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.