Events – HTML5 Doctor http://html5doctor.com helping you implement HTML5 today Tue, 21 Jun 2016 09:50:49 +0000 en-US hourly 1 Drag and Drop and Automatically Send to the Server https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/ https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/#comments Tue, 03 Apr 2012 13:30:17 +0000 http://html5doctor.com/?p=4500 I realised (when looking myself) that there are a lot of demos and tutorials that show you how to drag-and-drop a file into the browser and then render it on the page. They're often labelled as "drag-and-drop and upload", but they actually don't upload. This tutorial will take you that final step.

]]>
I realised (when looking myself) that there are a lot of demos and tutorials that show you how to drag-and-drop a file into the browser and then render it on the page. They're often labelled as "drag-and-drop and upload", but they actually don't upload. This tutorial will take you that final step.

I'll walk you through an example that you can play with: drag a file into the web page, and it'll be uploaded to the server instantly.

Tasks

Let's break this process down into specific tasks:

  1. Capture the drop event and read its data.
  2. Post that binary data to the server.
  3. Provide feedback on the progress of the upload.
  4. Optionally render a preview of what's being uploaded and its status.

To achieve all of this, we need the following HTML5 and non-HTML5 APIs:

  1. Drag and Drop
  2. FormData
  3. XHR progress event
  4. FileReader

Keep in mind that not all browsers support all of this technology today, but they're getting close. I just wanted to create a clear and complete tutorial on how to go the whole hog and upload that dropped file.

The end result: we're able to drop the file anywhere in the browser, we get a preview and progress of the upload, and it's a slick experience.

Drag and drop upload
Our drag-and-drop example page

Drag and Drop

Just as a forewarning, drag-and-drop has been known to be a bit of a killjoy. In fact, it's a nightmare, but I won't repeat what's been said before.

Our example is going to allow you to drag-and-drop a file anywhere within the browser. To achieve that, we need to attach our event listeners to the body or documentElement (i.e., the root HTML node). By listening on the documentElement, this code could be anywhere in the page, as documentElement will always exist. You can only listen on body once the <body> element has been encountered.

Here's the pattern of code we need to capture the drop event on the entire document:

var doc = document.documentElement;
doc.ondragover = function () { this.className = 'hover'; return false; };
doc.ondragend = function () { this.className = ''; return false; };
doc.ondrop = function (event) {
  event.preventDefault && event.preventDefault();
  this.className = '';

  // now do something with:
  var files = event.dataTransfer.files;

  return false;
};
Basic pattern for capturing drop events

I'm using the hover class so that I can toggle a tip explaining to the user that the file can be dropped on the page.

Inside the drop event, we can access the dropped files via event.dataTransfer.files.

An Alternative to Drag and Drop

Annoyingly, as I write this, I realise this combination of API requirements is currently only met by Chrome and Firefox. So, taking the test from Modernizr, we can test for support and provide our alternative:

var dndSupported = function () {
  var div = document.createElement('div');
  return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
};

if (!dndSupported()) {
  // take alternative route
}
Testing for drag-and-drop support

Instead of drag-and-drop, we can insert a file input element (I've given it an id of "upload"), and when its value is changed, the file can be scooped in:

document.getElementById('upload').onchange = function (event) {
  // `this` refers to the element the event fired upon
  var files = this.files;
};
An alternative to native drag-and-drop

You can see the equivalent is simply the files property of the HTMLInputElement object. This will give us access to the same file as the event.dataTransfer.files from the drop event.

Automatically Uploading the File

This is the neat bit, and it's painfully simple. We use a feature of the XHR2 spec: FormData. Once we create an instance of FormData, we can append items to it:

var formData = new FormData();
for (var i = 0; i < files.length; i++) {
  formData.append('file', files[i]);
}

// now post a new XHR request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.onload = function () {
  if (xhr.status === 200) {
    console.log('all done: ' + xhr.status);
  } else {
    console.log('Something went terribly wrong...');
  }
};

xhr.send(formData);
Creating and posting FormData

Yeah, that's it.†

Let's look at a couple of key things that are going on the above code.

formData.append('file', files[i]);

We're sending named parameters to our server, specifically an array of values called file. Obviously, you can call it what you want, but the file is the name your server will be looking for when it saves the uploaded file (or files).

xhr.onload = function () {
  if (xhr.status === 200) {
    console.log('all done: ' + xhr.status);
  } else {
    console.log('Something went terribly wrong...');
  }
};

If you're familiar with XHR, you'll notice we aren't listening to onreadystatechange, only onload — which is (in effect) a convenience function to let you know when the readyState is 4 (i.e., loaded!). You should still check and respond appropriately to the status code of the request to ensure it's 200 OK, rather than a 500 (internal server error) or 404 (not found) or anything else.

xhr.send(formData);

The nice trick here is that XHR has automatically set the encoding of the posted data to multipart/form-data. This encoding allows your server to read and save the files. It's like the encoding used when you send an attachment in an email.

Providing Feedback to the User

XHR2 now (flippin' finally) comes with a progress event. So if you're sending or retrieving a large file via XHR, you can tell the user how far along you are.

It's pretty simple. If you want to track the progress of the XHR request, listen to the progress event. One gotcha that caught me out for some time: I needed to track the progress of the upload, not the download. To do this properly, you need to listen for progress on the XHR upload object, as so:

xhr.upload.onprogress = function (event) {
  if (event.lengthComputable) {
    var complete = (event.loaded / event.total * 100 | 0);
    progress.value = progress.innerHTML = complete;
  }
};

xhr.onload = function () {
  // just in case we get stuck around 99%
  progress.value = progress.innerHTML = 100;
};
Providing feedback with XHR2's progress event

Note that instead of xhr.onprogress, we use xhr.upload.onprogess. When this event fires, we check that the event supports calculating the amount of data uploaded (the lengthComputable part), and then calculate the amount completed.

In my HTML, I'm using a <progress> element (similar to the <meter> element, but more semantically appropriate as we're presenting the progress of a task) to show the user how much of their file has been uploaded:

<progress id="progress" min="0" max="100" value="0">0</progress>

Note that I'm using innerHTML for browsers that don't yet support <progress>. Then with a dash of CSS-generated content, both the innerHTML and value of the progress can be the same (perhaps an over optimisation, but I was rather proud of myself at the time!).

And Finally, Rendering a Preview

As a nice addition, we'll give the user a preview of what we're uploading for them. It requires the File API — specifically the FileReader API.

As the drag-and-drop operation (or the input[type=file]) contains a file object, we can hand this over to the FileReader to get the contents of the file. If it's something like an image, we can get the Base64 data and give the user a preview. Or if it's text, we could render it in a <div>. The MIME type for the file is available as the type property on the file object.

So let's assume we only accept images. Here's the preview part that runs after the file has been received by the browser:

var acceptedTypes = {
  'image/png': true,
  'image/jpeg': true,
  'image/gif': true
};

if (acceptedTypes[file.type] === true) {
  var reader = new FileReader();
  reader.onload = function (event) {
    var image = new Image();
    image.src = event.target.result;
    image.width = 100; // a fake resize
    document.body.appendChild(image);
  };

  reader.readAsDataURL(file);
}
Rendering a preview of an uploaded image

We create the FileReader and give it a file to read. In the above example, I've used readAsDataURL, but you can also read files in plain text and binary formats (as per the spec).

When the reader has read the file and the data is available, it fires the load event, which in turn creates our new image.

The result of the file read action is in the event.target.result property. In the case of the readAsDataURL, the value is along the lines of data:image/png;base64,ABC....

Using All the Tools in the Shed

This example may be a little contrived for the article that I wanted to write. I've used many different technologies to do something that's a fairly common pattern on the web. In fact, it was because I had trouble finding a definitive source on uploading to the actual server (except, of course, as I wrote this article I found this example from back in late 2010!).

Hopefully, you'll see how each bit of tech can work together to create an application, but equally I hope that you can see where this would work if none or just some of the technology wasn't available. Make sure you detect functionality. Make sure you provide fallbacks. Make sure you develop responsibly.

Here's the final drag-and-drop and upload demo for you to play with.

Drag and Drop and Automatically Send to the Server originally appeared on HTML5 Doctor on April 3, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/feed/ 41
Server-Sent Events https://stevefaulkner.github.io/html5doctored/server-sent-events/ https://stevefaulkner.github.io/html5doctored/server-sent-events/#comments Tue, 24 Jan 2012 14:30:33 +0000 http://html5doctor.com/?p=4181

Related Posts:

]]>
We’ve already had a glimpse at Server-Sent Events (also known as EventSource†, and I’ll switch between the two to keep you on your toes) in my Methods of Communication article from last year. In this article, I want to delve in to more detail about the SSE API, demonstrate its features, and even show you how to polyfill browsers that lack EventSource support.

Server-Sent Events are real-time events emitted by the server and received by the browser. They’re similar to WebSockets in that they happen in real time, but they’re very much a one-way communication method from the server.

These events are similar to ordinary JavaScript events that occur in the browser — like click events — except we can control the name of the event and the data associated with it.

All the code for this article is available on github, and a live demo is available online.

† Is it Server-Sent Events or EventSource? Well, they both work. Server-Sent Events is the name of the API and specification. EventSource is the name of the JavaScript object you’re instantiating. It’s a bit like Ajax and XHR, where XHR refers to the XMLHttpRequest object…kinda.

Two notes: a) the uptime for this example is, I’m afraid, usually rather low — good for my server, bad for you. If you test the demo locally it will give you more interesting figures. b) IE6 isn’t supported in any of this article.

Possible Applications

A few simple examples of applications that could make use of Server-Sent Events:

  • A real-time chart of streaming stock prices
  • Real-time news coverage of an important event (posting links, tweets, and images)
  • A live Twitter wall fed by Twitter’s streaming API
  • A monitor for server statistics like uptime, health, and running processes

We’ll use the server monitor for this article’s examples. If this application were to be used in the wild, we could also check the EventSource‘s connection state to indicate when there’s a potential problem connecting to the server.

Overview of the API

The client-side API is rather simple, and it hands-down beats the insane hacks required to get real-time events to the browser back in the bad old days.

The main points of interest:

  • new EventSource(url) — this creates our EventSource object, which immediately starts listening for events on the given URL.
  • readyState — as with XHR, we have a readyState for the EventSource that tells us if we’re connecting (0), open (1), or closed (2).
  • onopen, onmessage — two events that we can listen for on the new EventSource object. By default, the message event will fire when new messages are received, unless the server explicitly sets the event type.
  • addEventListener — not only can we listen for the default message event, but we can also listen for custom messages using the addEventListener on the EventSource object, just as if we were listening for a click event.
  • event.data — as with most messaging APIs, the contents of the message reside in the data property of the event object. This is a string, so if we want to pass around an object, we need to encode and decode it with JSON.
  • close — closes the connection from the client side.

In the future, EventSource will also support CORS using an options argument to the EventSource object: { withCredentials: true }. But at the time of writing, no stable release includes this property.

Simple Example

Our simple web app will notify us of server status messages — things like the load average, number of currently connected users, and most CPU-intensive processes. If I were using this application in anger, I’d probably build server modules that emit specific event types when they cross specific thresholds, so that I’m only notified when something gets to warning level.

This snippet of JavaScript connects to our server, listens for messages, and handles the data that comes with the messages:

var source = new EventSource('/stats');
source.onopen = function () {
  connectionOpen(true);
};

source.onerror = function () {
  connectionOpen(false);
};

source.addEventListener('connections', updateConnections, false);
source.addEventListener('requests', updateRequests, false);
source.addEventListener('uptime', updateUptime, false);

source.onmessage = function (event) {
  // a message without a type was fired
};

Properties of Server-Sent Events

Server-Sent Events are more than just a one-way web socket. They have some unique features:

  • The connection stream is from the server and read-only. This suits lots of applications, some examples of which I listed above.
  • They use regular HTTP requests for the persistent connection, not a special protocol, which means we can polyfill using vanilla JavaScript.
  • If the connection drops, the EventSource fires an error event and automatically tries to reconnect. The server can also control the timeout before the client tries to reconnect.
  • Clients can send a unique ID with messages. When a client tries to reconnect after a dropped connection, it will send the last known ID. Then the server can see that the client missed n messages and send the backlog of missed messages on reconnect.

Message Format

A simple message doesn’t require much:

data: this is a simple message
<blank line>

Note that the end of a message is indicated by a blank line (obviously not the literal characters <blank line>).

For a message with multiple lines:

data: this is line one
data: and this is line two

You can send message IDs to be used if the connection is dropped:

id: 33
data: this is line one
data: this is line two

You can even send multiple messages in a single response so long as you separate the messages by blank lines:

id: 34
data: Remy is awesome

id: 35
data: Bruce is stinky

And you can specify your own event types (the above messages will all trigger the message event):

id: 36
event: price
data: 103.34

id: 37
event: news
data: Bruce sells his collection of replica bananas

You don’t have to worry about this structure on the client side. It only applies to the server, which I’ll touch on next.

Typical Server

I’m not going to give a full walkthrough of the server-side code, since this is an HTML5 web site :) But there are a few important and simple features that you need to know to build the server (you’ll need this part anyway if you’re going to use EventSource).

I’ve included all the files for this demo on GitHub for you to peruse at your own leisure, and I’ve also deployed a live example of this code.

Ideally, you should use a server that has an event loop. This means you should not use Apache, but instead use a platform such as Node.js (which I’ve used) or Twisted for Python.

Key properties:

  1. You can only accept EventSource requests if the HTTP request says it can accept the event-stream MIME type.
  2. You need to maintain a list of all the connected users in order to emit new events.
  3. You should listen for dropped connections and remove them from the list of connected users.
  4. You should optionally maintain a history of messages so that reconnecting clients can catch up on missed messages.

Here’s a sample of my Node.js based server. It’s using Connect (a simple webby framework for Node). When it receives a request for /stats, it calls the following function. I’ve commented the code so you can follow along:

function stats(request, response) {
  // only response to an event-stream if the request 
  // actually accepts an event-stream
  if (request.headers.accept == 'text/event-stream') {

    // send the header to tell the client that we're going
    // to be streaming content down the connection
    response.writeHead(200, {
      'content-type': 'text/event-stream',
      'cache-control': 'no-cache',
      'connection': 'keep-alive'
    });

    // support the polyfill - we'll come on to this later
    if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
      response.xhr = null;
    }

    // if there was a lastEventId sent in the header, send
    // the history of messages we've already stored up
    if (request.headers['last-event-id']) {
      var id = parseInt(request.headers['last-event-id']);
      for (var i = 0; i < history.length; i++) {
        if (history[i].id >= id) {
          sendSSE(response, history[i].id, history[i].event, history[i].message);
        }
      }
    } else {
      // if the client didn't send a lastEventId, it's the
      // first time they've come to our service, so send an
      // initial empty message with no id - this will reset
      // their id counter too.
      response.write('id\n\n');
    }

    // cache their connection - the response is where we write
    // to send messages
    connections.push(response);

    // send a broadcast message to all connected clients with
    // the total number of connections we have.
    broadcast('connections', connections.length);

    // if the connection closes to the client, remove them
    // from the connections array.
    request.on('close', function () {
      removeConnection(response);
    });
  } else {
    // if the client doesn't accept event-stream mime type,
    // send them the regular index.html page - you could do
    // anything here, including sending the client an error.
    response.writeHead(302, { location: "/index.html" });
    response.end();
  }
}

The important trick on the server is to ensure you don’t close the connection to the EventSource object. If you do, it will of course handle the closed connection, fire an error event, and try to reconnect. So you’ll just want to maintain the persistent connection.

Polyfills and Tweaks to the Server

There are two good polyfills I know of, and though I prefer the one I wrote, I’ll still lay them both out for you.

Yaffle’s Polyfill

The first is one by Yaffle (on github), available on github/Yaffle/eventsource.

The cons:

  • It doesn’t send the accepts header, and
  • It completely replaces the EventSource object, so even if your browser supports EventSource natively, this script will replace it. But there’s a good reason for that.

The pros:

  • It maintains a persistent connection (whereas the one we’re using doesn’t), and
  • More interestingly, it supports CORS (which I imagine is why it replaces the native EventSource).

These two pros are quite compelling. But when I was testing, I couldn’t get it working in IE7 (which was my minimum browser target), so that might be a blocker for you…or not.

Remy’s Polyfill

The second is my own, available on github.com/remy/polyfills.

The cons:

  • It uses polling, so once a small group of messages come down, it re-establishes the connection, which could lead to significant overhead (though less so on a Node-based server). You have to add about 4 extra lines to your server code.

The pros:

  • It doesn’t replace the native EventSource object (but that also implies that, for now, it won’t support CORS), and
  • It supports IE7.

Retrospectively, I might choose Yaffle’s polyfill over mine in the future if I wasn’t bothered about IE7 support.

Using the Polyfill

By including the EventSource.js JavaScript library before my client-side code, I just need a couple of small changes to my server-side code. Other than that, everything on the client side works without any changes (as a polyfill should work).

When posting the server’s reply to the client, instead of keeping the connection open, I include the following in my server when it’s finished writing the response:

// send the data (event type, id, message, etc)
response.write(data);

// if our response contains our custom xhr property, then...
if (response.hasOwnProperty('xhr')) {
  // clear any previous timers using the xhr prop as the value
  clearTimeout(response.xhr);

  // now set a timer for 1/4 second (abritrary number) that
  // then closes the connection and removes itself from the
  // connection array.
  // The delay is in place so that a burst of messages can 
  // go out on the same connection *before* it's closed.
  response.xhr = setTimeout(function () {
    response.end();
    removeConnection(response);
  }, 250);
}

Bugs?

The error event should always fire when the readyState changes, assuming you didn’t explicitly call the close method. This works nearly all the time, but in writing this article, I found a few edge cases where it doesn’t fire. In Chrome, if I put my machine to sleep and then woke it back up, it would close the connection but not fire the event, therefore never triggering a reconnection. As I said, this is an edge case and I’ll file a bug against it, so I don’t expect it to hang around for long.

Why Not Use WebSockets?

There are two reasons I’d advocate using EventSource over WebSockets, as they’re currently the two contenders for sending real-time events to the browser.

The first is that EventSource (as we saw earlier) works over regular HTTP and can therefore be replicated entirely using JavaScript if it’s not available natively. That means that we can polyfill browsers without support, like IE9.

The second is probably more important: you should always use the right technology for the job. If your real-time data is sourced from your web site, and the user doesn’t interact in real-time, it’s likely you need Server-Sent Events.

I recently saw a cool demo of snowflakes drifting down a web site. Each snowflake is a tweet based around the Christmas theme — like if someone mentions a particular Christmas-y term, it’s sucked in to the snowflake. Don’t get me wrong, I know this is a demo, and it’s very cool (if you wrote it, this is me sending you hugs), but it’s based on WebSockets. I’d suggest this demo should be based on EventSource since all the data is read-only and the user doesn’t interact with it at all.

The point: evaluate the technology against your problem, and aim to get good fit.

Server-Sent Events originally appeared on HTML5 Doctor on January 24, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/server-sent-events/feed/ 53
Get your HTML5 prescription filled at @media https://stevefaulkner.github.io/html5doctored/get-your-html5-prescription-filled-at-media/ https://stevefaulkner.github.io/html5doctored/get-your-html5-prescription-filled-at-media/#comments Tue, 03 May 2011 09:00:40 +0000 http://html5doctor.com/?p=3194

Related Posts:

]]>
I’m sure you can’t believe it, but there’s a chance for you to meet a real life HTML5 Doctor and ask them just about anything you want. Make it about HTML5, make it about related technologies/NEWT, it can even be about CSS3 – we won’t bite. It could even just be a general question like “how does Bruce Lawson get all the girls just using the new HTML5 elements?”

Return of the HTML5 clinic

We’re proud to tell you that (most of) the HTML5 Doctors will be attending @media 2011 and taking your questions. We’ve got our own desk (like last year) and we’ll be available between the conference talks. That way you can fill your head with lots of juicy information, and then trundle your way over to the handsome guys in the white jackets and ask your best HTML5 question (for which there will be a reward!†).

† Actually, we’re feeling kind, so anyone that asks a question, flashes us a kind smile or buys us a pint will get an exclusive little gift from your friendly doctor.

@media

If you’re wondering what @media is, you’ve either been hiding under a rock or you’re new to the business. None the less, we’re more than glad to tell you about it.

Founded in 2005, @media is recognised as one of the world’s leading conferences for web professionals. They pride themselves on keeping up to date on the latest moves in the design and development world. That means HTML5 has a big presence in their program of hand-picked world-leading experts.

Just some of the subjects that folks are speaking about during the two day conference:

Our special discount code

For those of you that don’t have a ticket to this excellent conference already, you might be thinking you’ve missed the early bird prices – fret not my dear friend, we have your back! We’ve managed to procure you a special discount code that will get you £100 off the current asking price. Just use the code HTML5DOCTOR and it’ll knock the price down for you: book it now.

If you’re coming along, drop us a comment below and we’ll see you there!

- Rich, Remy, Mike, Bruce & Jack, xxx

Get your HTML5 prescription filled at @media originally appeared on HTML5 Doctor on May 3, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/get-your-html5-prescription-filled-at-media/feed/ 2
Methods of communication https://stevefaulkner.github.io/html5doctored/methods-of-communication/ https://stevefaulkner.github.io/html5doctored/methods-of-communication/#comments Tue, 18 Jan 2011 14:30:41 +0000 http://html5doctor.com/?p=2847

Related Posts:

]]>
By now, you’ve surely realised that “HTML5” is so much more than just markup. There’s also an army of associated JavaScript APIs. Among the ranks are a few new technologies that open up how we communicate between client and server and across documents. Let’s take a look.

This post will be an overview of the technologies available, how well they’re currently supported, and, where possible, live demos. I’m going to touch on the following technologies:

  • XHR & XHR2 with CORS
  • Web Messaging
  • Web Sockets
  • Server Sent Events
  • Web Workers

Before I get on to the APIs, I want to outline a fairly common communication model that several of these APIs use.

A common communication event model

All event handlers (with the exception of XHR) receive an event object containing a data property. This property includes the data sent as part of the message.

The event model (again with the exception of XHR) is mostly based around onmessage and postMessage or send. For example:

// in the recipient code
recipient.onmessage = function (event) {
  console.log('received message: ' + event.data);
};

// from the sender code
recipient.postMessage('hi there'); // or recipient.send('hi there');

This is just a common model and isn’t the exactly the same among all these technologies. The two key similarities are that they use:

  • a sending method (postMessage or send) on the recipient object, and
  • an event handler that listens for the message event and receives an event object containing a data property.

Very importantly, most browsers only support sending strings from sender to recipient, so we often need to JSON stringify and parse if we want to send anything other than a string.

XHR & XHR2 with CORS

XHR can be both synchronous and asynchronous. XHR is the only API that (purposely) supports synchronous requests, meaning the execution of code will block until the callback fires.

There’s nothing particularly new about XHR, but in XHR2 we can handle uploads, and there’s a progress event to tell you how the upload or download is getting on.

The super shiny new toy in XHR2 is its support for Cross-Origin Resource Sharing (CORS). This means you can make an XHR request across domains, but only if the server you’re connecting to allows it.

The request is as you’d expect from XHR:

var client = new XMLHttpRequest();
client.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
    alert('The most awesome-est person to follow: ' + this.responseText);
  }
};
client.open('GET', '/no-cors');
client.send();

If our server responds with a CORS header, however, we can put our XHR responder on another server. So on the URL http://remysharp.com/demo/cors.php, I have the following PHP script:

<?php
header('Access-Control-Allow-Origin: *');
?>
@rem

This says that anyone can make an XHR request to this particular script. Now when I run the following code in a browser that supports XHR2, the cross domain request succeeds!

var client = new XMLHttpRequest();
client.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
    alert('The most awesome-est person to follow: ' + this.responseText);
  }
};
client.open('GET', 'http://remysharp.com/demo/cors.php');
client.send();

Here’s a live example of CORS. (You can also edit it here.)

Note that IE8 supports CORS, but not XHR2 (no surprise there then). You need to use their proprietary (booo!) XDomainRequest object. Nicholas C. Zakas has an excellent article explaining how to handle these differences.

XHR usage is pretty common already, but XHR2 with CORS is a winner over JSON-P, particularly as you have finer control over the request, can handle timeouts, and can handle errors correctly.

Support for XHR & XHR2 with CORS

  • XHR support is pretty solid nowadays (even though IE6 uses ActiveXObject to get it going)
  • XHR2 with CORS: Safari & MobileSafari, Firefox 3.5, Chrome and IE8 (via XDomainRequest)

postMessage

This API is older, but it’s very useful if you want to get around the XHR same-origin rules. If you have an <iframe> document that can accept onmessage events from your origin (i.e., your site), then you can communicate across domains (and origins).

For example, a page that accepts an onmessage event might contain code such as this:

window.onmessage = function (event) {
  if (event.origin == 'mytrustedsite.com') {
    alert('my trusted site said: ' + event.data);
  }
};

Now you can include an <iframe> that contains that code, and using the <iframe> DOM node, you can post to the <iframe>:

// where iframe is the actual iframe DOM node
iframe.contentWindow.postMessage("hello there", location.host);

This gives you the ability to send strings across two mutually trusted domains. (Remember that you can use JSON.stringify and JSON.parse to convert to an object to and from string format.)

Support for postMessage

  • Chrome
  • Safari
  • Opera
  • Firefox
  • IE8

Here’s a demo using postMessage.

There’s also a project called EasyXDM, which adds cross domain messaging to IE6 and upwards (along with all the other browsers) through the library’s abstraction. Definitely worth a look if this is a route you need to take.

Web Sockets

It’s my opinion that Web Sockets replaces Comet. Comet is a way of hacking the browser to giving us real-time server messages. The Web Sockets API provides that natively.

Web Sockets are used to send messages to and from the server — i.e., a bi-directional socket. In contrast to other similar technologies, with Web Sockets, you can go across domains, and you’re not bound by the same-origin policy. This means you can host your normal “apps” server while another server is for streaming content. Or you could host your own pages and connect to a live Twitter stream if your users turn on Web Socket support.

You can only send messages once the socket is open (duh). The communication model looks like this:

var ws = new WebSocket('ws://somesite.com/updates');

ws.onmessage = function (event) {
  alert(event.data);
};

ws.onopen = function () {
  ws.send('yay! we connected!');
};

Once the socket is closed, you can’t reuse it. Similarly, there’s no explicit method for opening a socket. That just happens when you create the WebSocket object.

This API is extremely simple. I most often get asked, “What do you put on the server side?” I personally use Node, but you could use an Nginx server or something like Jetty. I’m no expert on the latter servers, but I can vouch that a Node-based server is very, very simple to get going. The live demo below also includes a link to the code that I used to run the server.

Check out this demo of Web Sockets.

Support for Web Sockets

  • Chrome
  • Safari & MobileSafari

There’s also an excellent Flash poly-fill called web-socket-js. Drop this into an application and it provides Web Sockets support as if it were native. I’ve used this on a few projects of my own, and it works very well.

In early December 2010, there was a security notice posted about Web Sockets, and both Firefox and Opera pulled it from their upcoming releases. Mozilla have said that they expect Web Sockets to be back in Firefox by version 4.0.1.

Server-Sent Events

The Server-Sent Events API is something that originated from Opera back in 2006 and is used for pushing events from the server to the client. Note that the client cannot send messages to the server through an EventSource (SSE) — it can only listen for messages.

This API uses the onmessage model. It’s constructed using the EventSource object and is limited by the same origin rules:

var es = new EventSource('/sse');
es.onopen = function () {
  console.log('opened stream');
};

es.onmessage = function (event) {
  console.log('new message: ' + event.data);
};

The SSE automatically connects when you create the object (similar to Web Sockets), and once open will trigger the onopen event.

Here’s a live demo of Server-Sent Events

Here’s how this is to work: when a new message is pushed from the server to the client, it triggers the onmessage callback.

The key to your server is ensuring it doesn't close the connection on the client - the browser. Most of the examples around the web are doing this: closing the connection which tells the API to switch in to polling mode (note that this is the exact problem I hit when I first published this article).

When the API is in polling mode, it's no more different from an XHR poll, and the onopen will continually fire.

Al the code the server side can be viewed here: custom-echo.js (note that it's running on a Node.js server). There's a bit more code than you'd expect, because it's doing a few things: 1. Handling HTTP requests for files (and therefore is able to serve itself) 2. Handling the server-sent events and not closing the connection 3. Setting up a Web Socket server, and when a new connection comes in, it sends a server-sent event to all the currently connected sessions.

Support for Server-Sent Events

  • Opera 11
  • Safari & MobileSafari
  • Chrome

Web Workers

Web Workers are a way of creating a new thread of execution inside the browser. I’m including this because you still need to communicate with your Web Workers, and the method of communication is similar to some of those techniques discussed above. Do note, however, that this is not a method communicating from a client (browser) to a server. It’s more like there’s another browser window executing a particular block of JavaScript.

As an example of when to use a Web Worker, say you’re running a lot of JavaScript and the UI becomes unresponsive. The browser UI hangs because, in a way, it’s a “single-threaded application”. (Under the hood it isn’t really, but from a rendering and JavaScript perspective it is). This JavaScript task could be given to a Web Worker so that the UI can continue functioning.

It’s vital to understand that a Web Worker lives in a sand-boxed environment that doesn’t have access to things like the DOM. What’s more, you can only communicate with it using the onmessage and postMessage functions.

Our application can create and send messages to a worker using the following code:

var worker = new Worker('bigjob.js');
worker.onmessage = function (event) {
  alert('Message from worker: ' + event.data); // remember event.data is a string!
};

worker.postMessage('task=job1');

In the JavaScript file bigjob.js, we run some computationally intensive task and listen for messages in a way similar to what we’ve done in the previous examples. We can also post messages back to the invoking application:

this.onmessage = function (event) {
  var job = event.data;
  if (job == 'task=job1') {
    job1();
  } else if (job == 'task=job2') {
    job2();
  }
};

// just a pseudo example
function job1() {
  // do some big task
  while (working) {
    // continue task
    this.postMessage('job1 ' + amountComplete + '% complete');
  }
  this.postMessage('job1 100% complete');
}

There’s a lot more to Web Workers than just running a couple of small tasks, and no doubt we HTML5 Doctors will be posting a detailed article soon. This example just demonstrates how to communicate with Web Workers and how similar that is to the other technologies we’ve discussed here.

Support for Web Workers

  • Chrome
  • Safari
  • Opera
  • Firefox

A final word

Hopefully you agree that this is just the tip of the iceberg of communicating between client and server in HTML5. We’re no longer stuck with the same origin policy we had with vanilla Ajax. In fact, when you think about it, since IE8, we’ve actually had decent cross-domain messaging.

I’m personally most excited about Web Sockets and the support of CORS in services that have APIs, like Flickr, Twitter, and URL shorteners. What could you build with this?

Methods of communication originally appeared on HTML5 Doctor on January 18, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/methods-of-communication/feed/ 15
HTML5 Doctor at Web Directions @media https://stevefaulkner.github.io/html5doctored/web-directions-atmedia-2010/ https://stevefaulkner.github.io/html5doctored/web-directions-atmedia-2010/#comments Thu, 29 Apr 2010 13:15:59 +0000 http://html5doctor.com/?p=1865

Related Posts:

]]>
We doctors are excited to announce that we’re teaming up with Web Directions @media to bring you something very special. Not only are we a community partner for the event, but several of us will be running an HTML5 clinic to help cure your next generation markup ailments. We’ve also got some great discounts for the event to ensure you get the best deal available.

A Note about Web Directions @media

Web Directions @media Logo Founded in 2005, @media is recognised as one of the world’s leading conferences for web professionals. We pride ourselves on keeping up to date on the latest developments in the design and development world. That means HTML5 has a big presence in our program of hand-picked world-leading experts this year. Here’s a taste of some of the HTML5 related talks and workshops that are taking place:

  • HTML5 Doctor Bruce Lawson gives the lowdown on HTML5 for web designers, covering new semantic markup features, the HTML5 video and audio elements, and much more
  • Fellow clinician Remy Sharp gets out his scalpel and dissects what HTML5 has to offer for application developers. He’ll also be delivering a full-day workshop on the same topic
  • Jeremy Keith delivers a full-day workshop on semantic markup featuring HTML5
  • Jonathan Stark looks at how you can use web technologies including HTML5 to build native applications for platforms like Android, iPhone, and iPad
  • Matt Biddulph, founder of Dopplr, looks at adding geolocation to your web applications

Plus much, much more! For a complete rundown on what’s going on, see the full @media schedule.

HTML5 Clinic

All of us at HTML5 Doctor are very excited to announce that there will also be a special HTML5 clinic as part of the @media Expo. Led by various HTML5 Doctors, we’ll help cure what ails you when it comes to HTML5. Full details of the clinic will be made available shortly. We’ll be sure to let you know first.

Discount Codes

We’ve managed to get you a great discount on both the workshops and conference attendance. All you have to do is use the discount code ‘HTML5Dr‘ when booking and you’ll be eligible for the following:

  1. HTML5 Doctor Remy Sharp’s “HTML5 for Web App Developers” workshop for £275 (£50 off)
  2. Jeremy Keith’s “Get Semantic with Microformats and HTML5″ for £275 (£50 off)
  3. Conference attendance for £399 (before discount period ends [around May 7th])
  4. Conference attendance for £449 (after discount period ends)

So be sure to get the best deal on tickets and book before May 7th! If you’re going, let us know by leaving a comment below. We hope to see you all there!

HTML5 Doctor at Web Directions @media originally appeared on HTML5 Doctor on April 29, 2010.

]]>
https://stevefaulkner.github.io/html5doctored/web-directions-atmedia-2010/feed/ 4
HTML5 Doctor Speaking and Training Appearances https://stevefaulkner.github.io/html5doctored/speaking/ https://stevefaulkner.github.io/html5doctored/speaking/#comments Fri, 16 Apr 2010 13:30:40 +0000 http://html5doctor.com/?p=1577 Even after slaving away at the web's operating table, the HTML5 Doctors still find time to speak about HTML5 at industry events. We'd like to make sure you don't miss out on future chances to see the doctors in action.

]]>
Even after slaving away at the web’s operating table, the HTML5 Doctors still find time to speak about HTML5 at industry events. We’d like to make sure you don’t miss out on future chances to see the doctors in action.

For your convenience, we’ve put together a list of events where we’ll be speaking and even the ones we’re simply attending. Read on for some of our upcoming HTML5 appearances.

We’ll continue to maintain this page with new listings, so check back often. Otherwise you might miss us!

Upcoming Talks

Here are some of the HTML5 talks we will be giving at various events. Make sure you mark them down in your calendars!

In Attendance

Of course, we aren’t always talking. We still attend events to listen to talks ourselves. If you see us there, come and say hi.

Run an event? Get in touch!

If you organise an event or workshop and would like us to speak (or you’d just like to see us there), then we’d love to hear from you.

HTML5 Doctor Speaking and Training Appearances originally appeared on HTML5 Doctor on April 16, 2010.

]]>
https://stevefaulkner.github.io/html5doctored/speaking/feed/ 2