HTML5/JavaScript Communication APIs
This is a modal window.
The media could not be loaded, either because the server or network failed or because the format is not supported.
Formal Metadata
Title |
| |
Alternative Title |
| |
Title of Series | ||
Number of Parts | 170 | |
Author | ||
License | CC Attribution - NonCommercial - ShareAlike 3.0 Unported: You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this | |
Identifiers | 10.5446/50793 (DOI) | |
Publisher | ||
Release Date | ||
Language |
Content Metadata
Subject Area | ||
Genre | ||
Abstract |
|
NDC Oslo 2014121 / 170
2
3
5
6
8
11
12
16
21
22
23
27
31
35
37
42
43
45
47
48
49
50
52
54
56
57
58
61
65
66
67
71
74
77
80
81
83
84
85
87
88
89
90
91
94
95
96
97
98
100
102
107
108
112
114
115
116
118
120
121
122
123
126
127
128
130
133
135
137
138
139
140
141
142
143
144
145
147
148
149
150
153
155
156
157
158
159
160
161
162
163
166
169
170
00:00
TelecommunicationService (economics)Digital signalFocus (optics)World Wide Web ConsortiumSocket-SchnittstelleWeb browserEmailUniform resource locatorCommunications protocolTime domainBasis <Mathematik>Socket-SchnittstelleDifferent (Kate Ryan album)Web pageProcess (computing)Right angleMultiplication signSet (mathematics)Mechanism designVideoconferencingInformation securityJava appletArithmetic meanReplication (computing)Buffer overflowProjective planeWebsiteDialectServer (computing)Scripting languageGroup actionGoogolComa BerenicesContext awarenessHecke operatorWeb browserLogicComputer fileFood energyEvent horizonBitComputer configurationArmDomain nameTouchscreenStructural loadInformation and communications technologyLatent heatCausalityContent (media)Office suiteProduct (business)QuicksortOrder (biology)Query languageRaw image formatCodeSource codeSpectrum (functional analysis)Service (economics)ApproximationWeb applicationClient (computing)DigitizingWeb 2.0
05:45
Web browserEmailUniform resource locatorCommunications protocolTime domainComputer fileScripting languageCodeObject (grammar)Graphics tabletDifferent (Kate Ryan album)BitWeb pageServer (computing)Web 2.0Generic programmingAttribute grammarCASE <Informatik>Parameter (computer programming)Structural loadProxy serverJava appletScripting languageWeb applicationPoint (geometry)WebsiteAngleMobile appSquare numberWeb browserSinc functionFunctional (mathematics)Line (geometry)Web serviceService (economics)SoftwarePoisson-KlammerSet (mathematics)Right angleConstructor (object-oriented programming)Moment (mathematics)Information securityComputer fileProjective planeInheritance (object-oriented programming)Source codeDomain namePrincipal idealRow (database)Remote procedure callView (database)System callMedical imagingRule of inferenceWordProcess (computing)Arithmetic meanExtension (kinesiology)Goodness of fitComa BerenicesLimit (category theory)ArmReal numberComputer architectureControl flowException handlingSoftware developerComputer animation
11:29
Visual systemComputer iconMaizeScripting languageFunction (mathematics)BitRandom number generationWeb pageFile formatData typeComputer configurationError messageScripting languageVirtual machineGraphical user interfaceSet (mathematics)System callServer (computing)Functional (mathematics)Software testingPoint (geometry)Archaeological field surveyService (economics)Arrow of timeParameter (computer programming)Right angleDialectLocal ringProjective planeArmTouch typingCASE <Informatik>Domain nameComputer animation
13:46
ParsingContent (media)Source codeVideo game consoleCartesian coordinate systemParameter (computer programming)Information securityFile formatServer (computing)System callOcean currentCross-site scriptingFunctional (mathematics)Dependent and independent variablesOrder (biology)Event horizonSquare numberClosed setRandomizationContent (media)Scripting languageAlphabet (computer science)NumberService (economics)Computer architectureGroup actionWaveRadical (chemistry)Java appletArmPoisson-KlammerRight anglePoint (geometry)DigitizingInstance (computer science)Compilation albumComputer animation
15:53
Scripting languageParsingContent (media)Source codeVideo game consoleWeb browserTime domainComputer fileCodeService-oriented architectureInformation securityService (economics)Domain nameInformationCross-site scriptingContext awarenessMechanism designWeb browserReading (process)MalwareDigital photographyDifferent (Kate Ryan album)Process (computing)GoogolFamilyServer (computing)Scripting languageObject (grammar)Right angleExtension (kinesiology)Computer animation
18:13
Scripting languageMetreLemma (mathematics)Visual systemFunction (mathematics)Port scannerServer (computing)Computer virusView (database)Asynchronous Transfer ModeCodeProper mapComputer fileSystem callOrder (biology)Server (computing)Uniform resource locatorObject (grammar)Category of beingState of matterDependent and independent variablesWeb pageText editorInformation and communications technologyWeb browserFinite-state machineRight angleArithmetic meanWordLocal ringMixed realityService (economics)ResultantElectronic mailing listDifferent (Kate Ryan album)Line (geometry)Connected spaceSelf-organizationArmNetwork topologyComputer animation
21:51
Data typeContent (media)Element (mathematics)Video game consolePressureInformation and communications technologyUniform resource locatorControl flowSource codeEmailDependent and independent variablesTwin primeLatent heatZugriffskontrolleServer (computing)Web browserEmailWeb browserRevision controlDependent and independent variablesMathematicsObject (grammar)CodeServer (computing)Shared memoryService (economics)HTTP cookieCatastrophismRow (database)Limit (category theory)Local ringStructural loadLengthRight angleSoftware bugProcess (computing)Content (media)Disk read-and-write headProof theoryComputer animation
24:17
Video game consoleEmailDependent and independent variablesUniform resource locatorCache (computing)Graphical user interface9K33 OsaWeb browserExecution unitTwin primeWeb pageServer (computing)Control flowLocal ringWeb browserEmailScripting languageCASE <Informatik>WebsiteDefault (computer science)Graph coloringRight angleCore dumpResultantSystem callJava appletComputer animation
25:41
MIDIServer (computing)EmailDemo (music)Game controllerWeb browserMechanism designAuthenticationValidity (statistics)AuthorizationProduct (business)Electronic mailing listGoodness of fitInformationGraph coloringMathematicsString (computer science)Point (geometry)Local ringLatent heatWeightBitImplementationView (database)Functional (mathematics)Web serviceService (economics)Software testingSystem administratorVirtual machineWebsiteInheritance (object-oriented programming)Core dumpFiber bundleDisk read-and-write headWhiteboardQuicksortArithmetic progressionOperator (mathematics)ArmRight angleDecision tree learningCASE <Informatik>Food energyProcess (computing)Hecke operatorResultantCartesian coordinate systemState observerSoftware bugCellular automatonComputer animation
31:08
Latent heatContent (media)EmailZugriffskontrolleServer (computing)Web browserFlash memoryJava appletWeb pageWindowTime domainMechanism designInformation securityWebsiteCategory of beingParameter (computer programming)MetreMetropolitan area networkMenu (computing)Lemma (mathematics)Web pageMessage passingServer (computing)Domain nameUniform resource locatorComputer fileDifferent (Kate Ryan album)Identity managementComputer configurationRevision controlSource codeWebsiteTerm (mathematics)Slide ruleMobile appRootWeb 2.0Web browserEmailPhysical systemLocal ringMereologyOrder (biology)Flash memoryInformationFrame problemRouter (computing)View (database)Java appletCodeGoodness of fitPlug-in (computing)SoftwareInheritance (object-oriented programming)GUI widgetInterior (topology)PixelTap (transformer)Information and communications technologyPRINCE2Electronic mailing listGastropod shellArchaeological field surveyArmContent (media)Right angleProjective planeOnline helpQuicksortProcess (computing)Cycle (graph theory)Limit (category theory)Instance (computer science)Scripting languageDigitizingMultiplication signComputer animation
37:34
Time domainMechanism designContent (media)WindowWebsiteInformation securityCategory of beingParameter (computer programming)Scripting languageFunction (mathematics)Witt algebraInterior (topology)Clique-widthMessage passingScripting languageCodeView (database)Java appletWindowFrame problemContent (media)Web pageMathematicsParameter (computer programming)Configuration spaceObject (grammar)RandomizationInformationServer (computing)Arm2 (number)DialectRight angleLocal ringCorrespondence (mathematics)Computer animation
39:58
Time domainMechanism designWindowContent (media)Information securityWebsiteCategory of beingParameter (computer programming)Source codeServer (computing)Event horizonClient (computing)Message passingProcess (computing)Ext functorFunction (mathematics)Field (computer science)Line (geometry)Streaming mediaFile formatWeb browserEmailWeb browserEvent horizonServer (computing)Client (computing)Web pageWeb 2.0Default (computer science)Source codeMessage passingMechanism designRandom number generationInformation and communications technologyBitField (computer science)CodeFunctional (mathematics)Connected spaceDesign by contractMultiplication signWebsiteInterior (topology)Block (periodic table)CASE <Informatik>Patch (Unix)Artistic renderingSlide rule2 (number)Streaming mediaWindowCartesian coordinate systemMathematicsProjective planeOpen setShared memoryThread (computing)MereologyContent (media)Latent heatOrder (biology)Frame problemProcess (computing)Instance (computer science)Service (economics)Different (Kate Ryan album)ArmFile formatGodDatabaseSystem callStapeldateiFamilyObject (grammar)Form (programming)Software developerState of matterAddress spaceComputer animation
48:44
Context awarenessEvent horizonDependent and independent variablesContent (media)Data typeEmailIntegrated development environmentMaxima and minimaThread (computing)WindowFunction (mathematics)Message passingMenu (computing)Physical lawEvent horizon2 (number)Web pageMessage passingSource codeRight angleSet (mathematics)Computer animation
49:49
PressureEvent horizonDependent and independent variablesSource codeVideo game consoleUniform resource locatorEmailCodierung <Programmierung>Address spaceStreaming mediaFormal languageControl flowCache (computing)Local ringMenu (computing)Dependent and independent variablesGoodness of fitSystem callEvent horizonWeb browser2 (number)Arithmetic meanComputer configurationArchaeological field surveyMultiplication signRight angleComputer animation
50:59
Web browserEmailServer (computing)Event horizonStreaming mediaSocket-SchnittstelleDuplex (telecommunications)Information and communications technologyMetadataWeb 2.0Network socketDependent and independent variablesCommunications protocolRevision controlFunction (mathematics)Client (computing)Message passingApplication service providerWeightLibrary (computing)Installation artSample (statistics)Maxima and minimaSpacetimeOvalWindowPhysical systemTask (computing)Configuration spaceLemma (mathematics)Normed vector spaceInterior (topology)Table (information)Stack (abstract data type)Symbol tableWeb browserClient (computing)Server (computing)Information and communications technologyEvent horizonNetwork socketMessage passingRevision controlLatent heatConnected spaceKey (cryptography)Computer clusterGraph coloringCASE <Informatik>Focus (optics)Real-time operating systemWeb applicationSchlüsselverteilungArithmetic meanPoint (geometry)Object (grammar)ImplementationMereologySocket-SchnittstelleEmailWeb 2.0Validity (statistics)Demo (music)Goodness of fitInstance (computer science)Service (economics)Open setSoftware developerComputer configurationConstructor (object-oriented programming)Rule of inferenceWindowTable (information)Module (mathematics)Line (geometry)RoutingRegular graphCodeWeb pageNumberSubsetUniformer RaumSinc functionCommunications protocolRight angleMathematicsLibrary (computing)Application service providerConfiguration spaceInstallation artScripting languageForm (programming)PolygonProcess (computing)Information securityWebsiteDecision theoryDisk read-and-write headLengthSlide ruleView (database)Connectivity (graph theory)WeightProjective planeVideo gameWritingProduct (business)Endliche ModelltheorieArmStandard deviationThermal radiationRepetitionSampling (statistics)Java appletWordMeasurementDrag (physics)SummierbarkeitDemosceneSet (mathematics)Duplex (telecommunications)Dependent and independent variablesComputer animation
01:00:08
Server (computing)Socket-SchnittstelleEvent horizonDecision theoryTelecommunicationWeb 2.0Information and communications technologySlide ruleContent (media)SummierbarkeitRow (database)Decision theoryNetwork socketError messageComa BerenicesControl flowFlow separationWebsiteComputer animation
Transcript: English(auto-generated)
00:01
All right, so welcome. Thank you, thank you very much. Thank you for showing up and actually finding this room. I was looking at the agenda this morning and I was thinking, Didn't I have a talk today? I don't see that talk. Then I looked at the back, so thank you very much for showing up. To anyone sitting in the overflow room, if you're hearing my voice and wondering,
00:21
Where the heck is this guy? I'm in the top right corner, the smaller screen. Not one of the big screens, the smaller screen. So this is kind of like the elite session here. Not for everybody, so you have to have a certain amount of know-how in order to actually find the room and see the content. But I'm even more excited to talk to you about a topic
00:44
that is a little bit out of the limelight. I would like to talk about communication. So when you talk about communication in a context of JavaScript and HTML5, most of the time you think, well, communication, that's Ajax. Or you say, oh, communication, that's WebSockets, right?
01:01
So Ajax and WebSockets. Two, I guess, fascinating topics. However, there's a little bit more, and what I'd like to do today is I'd like to give you a great overview over various techniques that might be helpful in your projects to do communication, to facilitate communication between client and the server.
01:22
I mean, of course, simple communication can be always done by Ajax, and if you have the latest and greatest browser, and the latest and greatest server technologies, then you can use WebSockets, right? So we have two ends of the spectrum, but there is a little bit in between. I'd like to give you a kind of a history of communication issues with JavaScript
01:43
and show you techniques, some of them really old, some of them pretty new, and when they work, how they work, why they work, and if it's a good thing that they work or not. And my goal is that at the end you have a new tool set of techniques, and then you can decide, OK, which of these is worth using in your projects.
02:05
And, I mean, whether technology is right for you or not is really dependent on the project. There's no silver bullet. And that's why I would like to talk about this today. I am from a digital agency with offices in London, in Munich, Germany,
02:23
and we do websites and, well, other web-related stuff for our customers. So this is really an issue we have in our projects on a very frequent basis. And each of those technologies eventually was a good technology for one of our projects, right?
02:40
So it's not like I have one favorite and the other things I just read about yesterday. So this is really stuff that has proven to be successful for us, always depending on the specifics of the project at hand. Now, the agenda for today will look like this, approximately. So I talked to you about the status quo,
03:01
and one of the main issues or main facts is that we have something called SOP, same origin policy. So right after repeating what that is, we discussed ways to work around that, because that limits a certain amount of modern web applications. So we have a look at that.
03:21
We will have a look at something that not very few people know, yet it's pretty useful in some scenarios, so I'd really love to show you that, because you won't see that too often at a conference talk. So I'm really excited about that. So it's the messaging API. Even if you haven't heard that before, you may have seen it in a different context.
03:40
You'll see that. And then we'll have a look at more modern approaches. One is service and events. One is web sockets. So this is kind of what the overview I'd like to give you. So I do not want to focus on one specific technique alone, or one specific browser, but really give you a full set of options. And then at the end we can draw our own conclusions
04:00
what we want to use and what we do not want to use. Now, let's go back to the status quo. Now, the security system, and some of you know that I love to talk a lot about security. The security mechanism of JavaScript is, well, laughable at best, I think. On the other hand, when JavaScript was cobbled together in ten days,
04:23
you all know that, sorry, there was a security mechanism in place which still proves effective to this day. And the main security principle of JavaScript is the same origin policy, SLP.
04:41
So what's an origin? The origin is the protocol, so HTTP and HTTPS, different protocols, different origins. The domain, example.com and www.example.com, different domains, and port, well, AD, 443, 81, all different ports, different origins.
05:01
So that's an origin, right? JavaScript only has access to stuff, for now I just say stuff, to stuff that has the same origin as the origin of the JavaScript code. Now, what is the origin of the JavaScript code? Is it the server where the JavaScript code was loaded from? Sounds logical, right?
05:21
But it's wrong, because if that was true, if you load, say, jQuery from the Google CDN, jQuery couldn't access the DOM of your page. If the Google CDN was the origin of jQuery. Instead, the origin of any JavaScript code
05:40
is the origin of the HTML page that holds the JavaScript code or that references the JavaScript code. So for inline code, it's the HTML page's origin, obviously. And for external files, it's the HTML page that references those external files. That's super important. And that's the only reason why jQuery works, even if it doesn't run on your server. So the same origin policy says,
06:01
well, you know, JavaScript can access anything as long as the origin matches, is identical. This proves to be a very good idea. A very, very good idea. We'll discuss a little bit later on why. Because this prevented attacks that didn't exist yet. So back when that same origin policy was invented,
06:23
there was an attack being invented five years later, which is not as bad as it is because of the same origin policy. So really, hindsight. Amazing, amazing. I still can't believe this. Otherwise, the web would have been dead and we would have been at another conference probably today. So we'd all do, what's a non-web technology?
06:41
I don't know. Java or... Anyway, nothing against Java. So the same origin policy prevents that we access anything with a different origin. There's one exception, though. The SRC attribute. So it's more of an HTML thing then, of course. The SRC attribute is exempt from that same origin policy.
07:03
So that's why we can load JavaScript code from a different domain, from a different origin. That's why we can load remote images, remote stylesheets, and so on and so forth. So basically, that's where we are. And actually, it's a good thing, but it limits us to some extent.
07:21
Because more often than not, especially when we create a service-oriented architecture, we have some web services, and sometimes they have their own origin. They run on their own domain, maybe. Because it's not only our website that is consuming this API, it's also our app that's consuming the API,
07:41
and we may have some internal line of business software that consumes the APIs, and sometimes the server is not the same, or the origin is not the same as the one of our web app, right? Because the web app is only one UI for a set of services. So we may want to access a service even though the service is not in the same origin
08:03
as our web application. So this is a typical challenge from day-to-day projects. Now, basically what XML HTTP request does, the JavaScript object powering Ajax, is that, well, you can do HTTP requests, but still you have to use the same origin policy,
08:22
and you are limited by the same origin policy, more or less. So the question is, how can we circumvent that? I mean, there are server-side solutions, right? We could do a transparent proxy on our server. So if you have a web service on different origin.example.com, we could have a proxy on our origin server
08:40
that, well, you know, proxies everything to the other server. However, transparent proxies from a security point of view, it's probably not always the best idea. So I'd like to rule this out. I'd like to have a code solution. And actually there is a code solution and the code solution has been around since, I don't know, since JavaScript has been invented, actually.
09:00
The idea is this. As I mentioned, the src attribute is exempt from the same origin policy, right? So I can load JavaScript code from a remote server. That's a good start, but doesn't completely help us at the moment. I mean, what would happen? Let's have a look at this simple contrived example here.
09:21
I have an endpoint on my server, in that case a generic handler, and that generic handler returns some data I'd like to process with my JavaScript code. Now, what if the endpoint returned, let's say an array, angle brackets, sorry, square brackets 1, 2, 3?
09:40
Well, in that case, if included using script src equals, the return value 1, 2, 3 would lead to the browser instantiating an array with values 1, 2, 3. And then discarding the array right away, because it's not stored in a variable as such. In very old browsers like Netscape 6, you could override the array constructor.
10:01
So in that case you would actually gain access to that, but luckily this feature has been removed from modern browsers. So if we return data from the endpoint, it doesn't work. However, what we can do is, instead we return code, code that is run. A typical code looks like this. We call a function, I call it func,
10:21
but you can call whatever you want. But func is a user-land function, and this function is called by the code coming from the server. The one argument func receives is the actual data from our web service. So the web service doesn't return an array with values 1, 2, 3. The web service returns a function call,
10:41
and the first argument is the array 1, 2, 3. And of course, func, this function, is written by us. And it's called JSONP because, well, we return JSON from the server, and the P is the padding. The actual data is padded. It's padded by the function name.
11:01
And, well, the kind of consensus is that the function name is usually provided as a parameter. Sometimes it's called JSONP, sometimes it's called callback. And that is how JSONP principally works. Now, technically this is great, right?
11:20
Because it works right away. It works right away. And actually it's pretty easy to do, just to give you a brief idea of how easy this can be. And then we analyze why this is not always the best idea, otherwise the talk would be over already. I will just say, let's say, JSONP.HTML.
11:44
And to make it a bit quicker, I will, if I manage to control my touchpad, I will use jQuery. Because jQuery has a built-in support for JSONP in its Ajax calls.
12:01
So you can call $.ajax, and then you call the URL. Now, this is Visual Studio, and so once I run this project, it will spin up a test server using ISXpress on localhost port random number. What I also happen to have here on this machine is IS running on port 80. Now, port 80 and port random number
12:20
are different origins, obviously. So if I do a call to localhost port 80, or no port at all, and then whatever to some endpoint, .HTML, or whatever, or service, then it's a cross-domain request. Now, basically this doesn't work
12:41
because we violate the same origin policy. However, what we can do in jQuery is that we can provide a set of options. A set of options including a function that's called once we get data back from the server. But even more so, we can also provide the data type.
13:02
The data type is the format we expect back from the server, and the format we expect back from the server, in that specific case, is JSONP. So what this page now does is it does an Ajax request, so it does an HTTP request using JSONP
13:21
by dynamically injecting a script tag into the page, and by saying, well, we expect JSONP back, the way the script is called is very, very special. Actually, let's try that out. I have Chrome here, and I will open up the Chrome tools,
13:40
and then I run this again. We get an error here because I don't have this endpoint, but let's have a closer look at this endpoint, right? So we have an additional argument to that call to endpoint.HTML. We have callback equals, and then jQuery, and a random number, underscore,
14:00
and then the current date in epoch format. So what this does is jQuery needs to process the data coming back from the server, right? Because the server is expected not to return just data, it's to return a function call. But what should that function be called?
14:21
So jQuery, in order to avoid overriding or overlapping of those names, jQuery just generates a random function name and expects that the data coming back from the server looks like this. jQuery 2, 1, 1, 0, 0, 0, et cetera, et cetera, et cetera, parentheses, square brackets, 1, 2, 3, closing square brackets, closing parentheses. So that's the basic idea.
14:41
So if the server returns this very value, then the content of that function call would be provided to our success event handler in jQuery. So really, really easy to do, actually. The only thing you have to be super careful about here is, and again, I'm wearing my security hat for a minute,
15:03
so you provide something like a function name, and I've seen, I frequently do audits, security audits, and what I see quite a lot is that people write this JCP endpoint and they just do a, whatever, response dot write of the callback argument. What's this technically called?
15:21
Exactly, that's cross-site scripting, right? Because if the name happens to contain a script tag, for instance, then we would have JavaScript which runs on that very origin, right? So cross-site scripting. So you have to be very, very careful about the name. The jQuery function or callback function name is kind of predictable, right? jQuery plus a couple of numbers and the underscore,
15:42
so the alphabet here is very limited, uppercase, lowercase, digits, and underscore, so you can very, very easily whitelist that. But just to give you an idea, so that's great, right? So that's wonderful. It's a brilliant idea, actually. End of the talk, thank you very much. Well, kind of not. I think it is a hack because, I mean, it's a service.
16:02
I expect from a service and a service-oriented architecture that the service returns data. The service doesn't return code because the security mechanism of JavaScript, I mean, it does make sense, right? Because the code runs in my security context, in the security context of my domain, so I have to trust this code
16:22
because the browser trusts this code and grants this code access to anything on my origin. Would you trust a remote server? Well, some of you obviously do because you load jQuery from the Google CDN. If Google decided to inject some malicious code into jQuery for, I don't know which reason,
16:43
then that code would run on your domain with the security context of your domain. Well, I mean, I have to say, I trust Google, too, to some extent, so as long as the Google CDN doesn't wear Google glasses, then I'm more than happy to load jQuery from there, and probably many of you do, too, right? But still, you get code from somewhere else,
17:03
so you have to trust that code. Also, since we have to use script-src, we're using get. HTTP get. HTTP get is great as long as you only retrieve data. But what if you would like to delete something on the server? What if you want to, whatever,
17:21
update information on the server? You shouldn't use get for that because cross-site request forgery might be highly likely if you do. And, I mean, if you adhere to REST principles, then, you know, get is for reading and nothing else. So we are limited to get, and this might be an issue, very well an issue.
17:42
So this is the first step, and, I mean, it's an old technique, but in many scenarios, it is pretty useful for receiving data, and it works in Netscape, too. So if Ajax, which works in Netscape, too, Ajax was only implemented in Firefox 1 and IE 5 or something. I mean, well, who is using Firefox 1 or IE 5 these days?
18:03
Hopefully no one, but still, I mean, it's a good old technique, so I want to start with that. Now, I mentioned that I... Oh, actually, before we look at that slide, let's try something else out. So I mentioned that the XML HTTP request object
18:21
is also restricted by the same origin policy. Now, I have to tell you, how do I put this in correct, proper words? I don't want to say I was lying to you, but I was bending the truth. Is that okay? Okay, I was bending the truth. All right.
18:41
So the thing is this. Actually, let's do a simple Ajax call, because this shows pretty well what's happening. So how do I do an Ajax call? I instantiate XML HTTP requests, the object, and then I open a, let's say, GET connection. To our mode server, I'm using localhost,
19:00
and I happen to have a folder HTML5, communication, and then, let's say, a PHP script. I'm using PHP just to see that it's a different server, right? So we don't mix them up. So I call a script, which I'm about to write, using an asynchronous call. I send the request, and before I send the request,
19:21
we have this weird order. I look if the state machine that tells me what the XML HTTP request object is currently doing has reached the value 4, which means data is there. I can process the data. So if the ready state of that object has value 4, I can now access the data coming back from the server.
19:42
So let's say data from server colon plus the response text. All right. This is simple Ajax. But it won't work, right? Because we are here on localhost. Do I still have the browser open? Localhost 24139 calling localhost port 80.
20:05
Well, that doesn't seem to work. I have an editor here, which actually allows me to write or create files. I just create a file course.php. So this is the other server.
20:22
Just text support is fine. And it just says, hello world. Can you see it all right? So I have the file course.php, and it says hello world. And we can try to call that file. So let's just say localhost HTML5 communication course.php.
20:43
And well, it says hello world, right? So the file works. It doesn't do anything, but it works. Isn't that great? I wish I could say that about all my code. Now, what happens if I'm running this? It tries to call that same URL I've just opened. But, well, I shouldn't get any data back. So let's try this out.
21:01
View page and browser. And I say, wow, I get a result. Oh, no, I lied to you. Oh, sorry. But on the other hand, I may have lied to you, but my code is bad, too, because it says data from the server and nothing. This is getting weirder by the minute.
21:21
I'm really confused right now. So I said the same origin policy prevents us from doing that request, but the request was sent. Now, I also said, well, if we do an AJAX request, we get data back from the server, and it's in that property of the XML HTTP request object, but there's nothing in there.
21:40
This is getting weirder by the minute. Let's see if we find a proper way out of this. So I reload this again. And, well, we do have a request to course.php. So, oh, we got a request. A request was sent to the server, but for some reason the request was canceled.
22:04
Weirder by the minute. All right. So we have some headers. These are the request headers that I sent to the server, and the data I got back is empty, failed to load response data. If you tried this in Firefox and were using Firebug,
22:21
it would look the same. So you would get a response back. You could also have a look at the response headers, and you would see that one of the response headers was content-length and a value of hello blank world 11. But still the response tab would be blank. Now, the reason behind that is that modern browsers
22:42
support XML HTTP request version 2. Version 2 changes a couple of things, so we can avoid this onReadyState change. We can just use onLoad, as, you know, we do in the rest of JavaScript APIs. And also, this object supports something new,
23:01
which is called CORS, cross-origin resource sharing. I mean, why do we have the same origin policy? Well, it was invented earlier than the attack, but of course we use it, or we are happy that there is a same origin policy, to prevent cross-site request forgery, CSRF, or sometimes called CSRF, right?
23:22
Because otherwise JavaScript code could, well, you know, send arbitrary HTTP requests to any service and would automatically send along all cookies we have with that server, so catastrophe is looming. What CORS does is, maybe we want to send a cross-domain request,
23:42
but technically it could be an attack. Who is attacked? Well, essentially the remote server is attacked, because the remote server gets a request but doesn't know, has the user really wanted that request, or is it some malicious JavaScript code? If the server says, well, no, I'm fine with getting a request
24:02
via cross-domain, then the server can kind of whitelist or let through that request. How does that work? Let's briefly go back to Chrome, and we saw here, actually let me increase this a little bit, we saw here that the browser automatically sent a new header,
24:22
a header that's usually not sent with an HTTP request, the origin header. We said, OK, by the way, dear local host port 80, this is a cross-domain request coming from presumably local host port 24139. So we tell the server, oh, by the way, this is a cross-domain request,
24:42
but the caller, the origin of the HTML page that contains the JavaScript that does the call, the caller is of origin HTTP local host 24139. Now, the server can now, well, do a couple of things. The first thing the server could do is do nothing.
25:01
This is the default case. The default case, because when course was invented, there were already a lot of websites out there, so default case needs to be secure by default. The default case is that, well, the server doesn't do anything, just sends a reply, and browsers are configured that way, that since it's a cross-domain request,
25:21
JavaScript doesn't get access to the data from the server. Otherwise we would break same origin policy. If, however, the server specifically wants cross-domain request, the server has to unlock those cross-domain requests. How does the server unlock those? Well, the server, and that's the reason why I'm using PHP script here,
25:44
or I could use any other technology as well, the server has to send a specific HTTP header. If the server sends the specific HTTP header, it instructs the browser to say, yeah, fine, I'm good. Now what does the server need to do? Well, I know we could, of course, do this in .NET.
26:02
I'll do it in PHP, but don't worry, I'll explain exactly what I'm doing. We have a function in PHP called header, which sends a header string back to the server. And we have a specific header for course. It's called access-control-allow-origin. Now that's a short name.
26:21
And the value of access-control-allow-origin needs to be the origin of the caller. Only if it's the origin of the caller, and the browser validates that, only then the browser gets access to that data. So we would need to write now HTTP localhost, port 24, I think, 129.
26:41
And then run this again. Before we do that, before we do that, maybe one more thing. Never tell anybody, I told you that, so probably I go a little bit out of the camera view now, because then it's less embarrassing. For testing and demos only. And your machine will melt
27:00
if you do this for a production website. It only works in demos. Trust me with that. Only in demos. You can use a wildcard. Only in demos. Seriously, seriously. There will be a thunderstorm, right? Over your house, only over your house, right? If you do this in production. Only for demos, you can just say,
27:22
oh, what the heck, anybody can talk to me. Well, actually, given there are some web services which are public and maybe have no authentication, so they don't mind if they get requests from arbitrary people, arbitrary browsers. But still, don't do this in production. Still, I want to show you that. Okay, so access control origin is now the header being sent out.
27:42
So let's try to run this again, and now you immediately see we do get data back from the server, just because of that header. That HTTP request is not aborted anymore. No red color here. Instead, now the request went through. Implementing this in the browser is trivial, because you don't have to do anything.
28:01
Implementing the server might be a bit more complicated. I mean, this case with get is okay. You check, is there an origin header? Then you have a list of valid origin headers, and, well, then there's a white list, so if the origin header is in your list of trusted headers, then you send back the data. It's a bit more complicated with post,
28:22
because the thing is, and that's another reason why it's super important that get requests do not change anything on your website, or on your server. The get request is still sent. Even if the server doesn't return anything, the get request is still sent. So if the get request changes anything on your server,
28:43
you're prone to cross-site request forgery. With post requests, it's different. So the mechanism that generally works here is, I mean, a post request is not just sent, because if a post request was sent, usually with a post request we are not interested in result, we just want to send or change something. Now, if there's a post request,
29:01
the browser first sends a get request, a so-called pre-flighted request. And if the get request is answered correctly with that header, et cetera, then in the next step the post request is being sent. That kind of works out. So from the server point of view, there are little things, a little bit what you need to implement. Microsoft has an implementation for that.
29:22
I think it was also a third-party contribution, so it's not that easy. And if you have this idea, well, after one week of conference, I will sleep for ten hours. This was a long week. I'll sleep for ten hours straight. But you have to get up early tomorrow.
29:40
Don't worry. Read the course specification, because it will keep you up at night. There are things in there which really make me shiver. It's kind of like hell on earth. It's really, really complex and stuff in there, so I can only recommend you have a look at that. But again, don't blame me. So that's the course principle. One thing that's very important to me is
30:04
this origin header is sent automatically by the browser. So it's a good thing. However, you cannot trust this header. Don't do authorization or authentication based on that header, because everyone can send an HTTP request. Everyone can make up any HTTP headers.
30:22
So once in an audit, true story, the customer had a service endpoint, and they were using CORS, and basically they had logic like if the origin header contains whatever, local hosts port this and that, then, you know, grant admin access and send all kind of debug information.
30:41
It's trivial to tamper with the origin header to craft an HTTP request that contains a specific origin header. So don't trust this. You have to have another solution for authentication authorization. But if the header is sent, and the user is authenticated anyway,
31:00
then you can send the access control allow origin header, and then everything is good. So that's CORS, and I think it's a very important technique, and kind of leaves the web as secure, insecure as it is, but gives us still an option to overcome the same origin policy.
31:21
And this is really super important, a super important aspect, as long, again, as you actually use the HTTP header in order to whitelist that. Now, if you need a fallback solution, maybe for older browsers that don't support CORS yet, there is another means for cross-domain requests.
31:41
I just would like to very briefly touch that. Of course, you can use a plugin. So, for the younger people in the room, a plugin was what your parents were using on websites to show dynamic content, like pre-HTML5. So, yeah, it's not a solution that's, let's say, viable for long term
32:01
or even for mid term, but still, it might be a fallback. If you are interested in such a fallback and would like to implement this, and this is the only reason why I put the slide into the deck, the origin definition is different for a plugin. So, if you have a Flash movie, Flash app, if you have a Java applet, or if you have a Silverlight application,
32:22
the origin is the server where the app comes from, not the HTML page. That's different, different than in JavaScript. Once you know what the origin is, then there is a policy system that works with a policy file in the root folder of the web server. So, there might be a solution.
32:41
IE8 has also X domain request as an object. So, even though IE8, for instance, doesn't support XML HEP request version 2 yet, X domain request kind of does the same thing. So, it might be a solution, but still. So, now we can do cross-domain requests, which is fine, but the same origin policy limits us also in another aspect,
33:02
when we'd like to talk not only via HTTP, but if we'd like to have different widgets, different parts of our page, different browser tabs even, to communicate with each other. And, again, the same origin policy says, let's say I have an HTML page,
33:20
and in that HTML page I have an iframe with another HTML page. I cannot communicate with that. Actually, let's set this up real quick. So, I'm adding a new file, and in that file I just call it messaging-sender.html,
33:41
and that's a file, and that file will hold, and also only elder people in the room know what it is, an iframe. Well, actually, iframes are kind of still used. Frames are a thing of the past, so I call this, like, F, like iframe, is that a good name? And, what do I say, 300 pixels,
34:02
times, I don't know, maybe 300 pixels again, doesn't make sense. And what the iframe also has is a page which is loaded in the iframe, and that page has a URL. Again, I'm using my local host server, HTML5, communication, messaging-receiver.html.
34:23
So, I'm loading a page from a different server, which is fine, right? Because it's the src attribute, it still works. Now, let's go here. Let's add a new HTML page, and in that HTML page called messaging-receiver.html,
34:43
I just say, whatever, h1-receiver, right? So, nothing spectacular, I guess, but if you run this in a browser, the page isn't loaded. Do I have a typo?
35:02
Didn't I save? Messaging. Do you see a spot, any error? That's irritating. Iframe info. Identity not verified. Well, I don't care, actually, but frame source.
35:20
Frame source is empty. Let's see. Doesn't it work? Actually, that's really unfortunate. Let me see if the file is there otherwise. So, the file is there, and I don't have a typo, I believe. So, let's see. If you just call the...
35:41
Now, view source doesn't help. HTTP... No HTTPS. Not on the Sloan network. Let's try again. Messaging-receiver.html. Doesn't show the page. I don't know, maybe my server kind of went down or something.
36:00
That's really weird, because the file is okay. Let's see. So, this still works. Okay, this is the other server, actually. This works as well. Interesting. Okay, yeah, sorry for that. I don't know why it doesn't want that. But no problem, because I will still be able to show you the API, and you may have seen, as I promised, you may have seen the API before.
36:23
Now, the thing is this. We now, technically, if it would load, we load now a file into this iframe, right? The origin of the HTML page is localhost colon blah blah blah blah blah. The origin of the iframe is localhost port 80.
36:46
Right? So, the thing is that the iframe has a different origin, which is no problem as long as we are using the src attribute, as we just did. However, there's a catch, of course.
37:01
If you would like to send data to that iframe, that doesn't work, because the iframe has a different origin. Now, let's just imagine that that iframe contains a widget of ours and would like to communicate with that widget. So, how do we do that? Because, technically, we can't, because the widget doesn't have access to the outer HTML page
37:23
and the JavaScript code in the outer HTML page doesn't have access to the widget, thanks to some origin policy. Now, there is a way around that, and we have to have a look at the way on the slides, and the idea is this. We have the so-called messaging API,
37:40
which is a very, very simple API, which is used in a lot of places in JavaScript, and this allows us to send a message to a different window, a different tab, and an iframe, and it would look like this. Let me just give you the code in the download.
38:02
Well, probably it's a configuration issue with my other server, so it should work right away anyway. So, let's just say, once the page has been fully loaded, which is required since we access the DOM, I just access the iframe and then the content window.
38:24
So, this corresponds to the window object of the HTML page being loaded in the iframe. Now, again, I cannot access anything thanks to the same origin policy. However, the messaging API,
38:43
which works in all modern browsers, allows me to do something like this. Iframe.postMessage allows me to send a message to that iframe. Okay, so far, so good, whatever. I would send any message, let's say math random. And I have to provide a second argument, and the second argument is the origin of the target.
39:06
I would like to send a message into that iframe, but, I mean, I'm not sure if the iframe holds content from the origin I'd like to send data to. So maybe the page in the iframe originally had cross-site scripting issues
39:21
and has now been redirected to another page. I don't want to send my sensitive information to another domain, I just want to send it to my explicit origin, so I have to provide the origin. So in my case, it's localhost and no port. So I'm sending a message now to the iframe. What happens next? Nothing.
39:41
Because, well, I send a message, but the iframe couldn't care less. Right? That's just a page in the iframe. And maybe that page in the iframe doesn't care as well. If the page in the iframe cares, then, in that specific case, I can do something about this. So, in that page here, what I would do is just
40:03
wait for the message event to be fired. Because once I do get such a post message information, the message event is fired, and now I can access, whatever, let's say, alert e.data.
40:22
And I now could access the random number. I could also check the origin, right? The origin of the sender. So I could also check, okay, I just got data. Where did I get that data from? Was it really my trusted server localhost 24139 and not the known spammer website localhost port 24138?
40:42
So I could check that I can process the data. I could also send data back, something like self.postMessage, and then I would send a message back to the outer HTML page. The outer HTML page then would just need to listen to the message event again. So I can send data back and forth,
41:01
especially in that rigid situation. And we seem to have more and more customers who have a kind of solution like this because they have just a block of functionalities and the blocks are sometimes on different servers, especially in larger companies. This is a great way of doing communication in a standardized fashion. And again, this is something you won't see very often,
41:21
but it just works beautifully and that makes it so appealing also to me. And that's why I wanted to definitely show you showed up today. So this is what the messaging API does. Now, you may have seen the messaging API before, postMessage, listening to the message event.
41:43
Someone here has seen this before? Yes, please, just shout. Just shout. We are among us. Yeah, web workers, exactly. So web workers, a mechanism, in case you haven't seen it before, I believe you do.
42:01
So web workers are a mechanism to run JavaScript code in a kind of background thread. I have to quote the thread because technically browsers are multithreaded, but the way they execute JavaScript not always is. But code is deferred in the background and so it doesn't block UI rendering. And they're using exactly the same mechanisms.
42:22
So you instantiate such a worker and then postMessage message event, postMessage message event. So really, really simple API. And I mean, if you think about what HTML5 and JavaScript in general just offer us in the last few years, the API is usually really simple. All the heavy lifting is done by the browsers.
42:44
And sometimes by the server. Okay, so this is the messaging API and also web workers. I added two slides about web workers to slide deck, so you just have the full picture here. But I don't want to discuss web workers today. Instead, I'd like to just discuss something else
43:01
which you might not see very often. And it's a fascinating technology with one catch. Let's talk about that catch later. I'd like to keep you in a good mood at least for 60 seconds before I tell you the bad news, right? So the idea is, so far, I mean, we now can do cross-domain requests,
43:21
but we are still using HTTP. And we are still using pull. We pull data. We cannot push data from the server. So this is a problem, right? This is a problem for modern applications that have to change on the client when on the server and the database, for instance, and the server something changes. And there are a couple of workarounds which are in use.
43:45
One of the workarounds is long polling. So what you basically do is you do one HTTP request, for instance, with XML HTTP request or with an iframe, and the request just doesn't send data. It sends a bit of data but keeps the connection open and then sends another bit of data
44:01
and then sends another bit of data. So you have this one long-running connection, and you get data bits and data bits and data bits. So it's kind of like push from the server as long as the client keeps the connection open. Now, if you were a web browser and you connect to a server and this takes ten minutes,
44:21
ten minutes still sending data, and it's no download, what would you do as a browser? Yes, exactly, you would close the connection because it's a waste of resources. So there are some issues involved with that. And so modern browsers have some kind of workarounds or new techniques that allow us these kind of long polling requests.
44:41
And one thing that was part of the HTML5 specification originally is called server-sent events. Actually, it's a brilliant, brilliant idea. And the idea is that, well, you get data packaged from the server and the browser, well, keeps the connection open. When the connection is closed, maybe due to an activity or due to a shortage of resources, no worry,
45:04
the browser automatically instantiates the connection again. So again, as a JavaScript developer, you don't have to do anything. Just use a very simple API. The browser takes care of the rest. I show you first the JavaScript API. Really, really simple.
45:21
So you have the event source object. Well, object, it's JavaScript. Let's just call it object. And then, well, you have an endpoint. So that's a URL, basically. And then you instantiate that. And then you just wait for a message event. And in the message event, in the event arcs, you get the data, origin as well, et cetera, et cetera.
45:43
Interesting. It works in all relevant browsers. No, let's say in all modern browsers. It works in all modern browsers. Which, of course, is the problem. No, I promised when I signed the contract for here, I promised that this time I would not rant about IE.
46:02
I promised, so I won't do. So let me rephrase that. Works in all browsers, it doesn't work in IE, unfortunately. Unfortunately, and they won't add it. In many cases, of course, this might be a deal breaker. It also took some of the browsers quite some time to implement that. So for instance, the Firefox team, I think,
46:21
they added it in 2011 or 12. And they started, the first patch was, I think, provided by a community member in 2006. So really, it took them some time to get it right and do we put it in? Don't we put it in? Now everybody has put it in. And we have used that with great success, actually, for some solutions, especially mobile solutions,
46:40
where we could exclude IE. I remember one project where just the market share back then of Windows Phone was that way that, well, we could happily ditch IE. I still would like to show you that briefly because I really like the way this is implemented because I think the idea is so clever.
47:02
So what they're doing is this. We have a stream format, right? We have a specific content type, text slash event-stream. And then we can set a couple of fields in a almost Windows 3.1 INI style syntax. Field colon value. So this is a block of data. ID colon 123, data colon ABC.
47:24
ID colon 456, events data colon DEF. So I can send data packages with data or with events. So I can trigger events. I have a server event and then trigger some code in the client which listens to those events. And the idea is that each of those packages
47:42
has an ID, hopefully an ascending ID. And probably you have an idea now what happens next. What if the browser disconnects the connection to the server? What then, right? Well, the browser reestablishes the connection.
48:02
Now the browser knows which of those data packages have already been received by the browser. So when the browser reconnects, and by default this happens every few seconds in order to avoid resource exhaustion, the browser also sends a new HTTP header, last event ID.
48:24
So the browser tells the server which ID was the last one. So the server, when reconnected, it's a new request for the server, the server only sends newer data. I think that's pretty interesting. So let's see if we can try this out in a very limited fashion.
48:41
So really this is a bit of a fabricated way of doing things. So what I'm doing here is I have a simple handler and I read out the last event ID header, as you can see here. And basically I just have three data packages. I have one, two, three, four, five, six, and further down seven, eight, nine.
49:01
And what I do is, well, if the last event ID is not set or smaller than one for three, I send package one for three. If it's smaller than four, five, six, I send package four, five, six, et cetera, et cetera. And the HTML page that is using that, the HTML page, you know, just, well, connects to the event source and then waits for a message and waits for an event.
49:21
So I can also listen to those events being set. And just that you see what is happening here, given that, let me load that again, so that you'll see. So we have a first request here to event source, ashx, and what you can see is,
49:44
so this is the first request, right? And a couple of seconds later we have a second request, sorry, I have to zoom in again. And in that second request, we have last event ID equals one, two, three, right? So we made a second request. What's the response of that request? Oh, it's ID four, five, six.
50:02
Good. So the third request, this is that one, sends the last event ID was four, five, six. So what's the response? Seven, eight, nine. So the next request says last event ID is seven, eight, nine, and now, well, we don't return anything, right? Just because we don't have any more data,
50:21
but still, every few seconds, we get a new request. So we're constantly polling the server, is there new data, is there new data, and if there's new data, we kind of get it right away. And the browser does that. So no need for us to set timeout or set interval calls to do ajax requests, and then, you know,
50:40
do we have concurrent requests, which might be a problem, and what timeout value do we choose, I mean, do we use 100 milliseconds, which is stupid, because the HTTP request, usually the handshake takes longer, right? So this is an option, right? This is still an option. So I find this a really, really interesting technique,
51:00
and as I mentioned before, we have successfully used it, and you won't see that too often, so I think it's an interesting piece in your tool set, as long as you can avoid IE or have a solution that kind of takes care of everything. Now finally, there's one more thing, right?
51:21
You know, there's this company who always had one more thing until a couple of years ago. Well, same here. I say it's one more thing, but actually it's kind of the same thing, but in a different color. No, of course, I still have to talk about WebSockets. So WebSockets are, of all those techniques involved, probably is the most modern one, of course,
51:41
and in many cases it's the best one. Not in all, but in many cases. So WebSockets, as you know, allows us full-duplex communication. So, I mean, HTTP has some problems, as you know, handshake, no push from the server, et cetera. WebSockets does the following thing.
52:01
They start with HTTP, right? So we can use TCP port 80, which is already whitelisted in Firewall, usually. But then what happens, if we have at least IE 10 or any other modern browser, what happens then is the following thing. So this is taken directly from the RFC, from the specification.
52:24
So this is the request. So a WebSocket request starts with a typical HTTP request, but it's using the upgrade header. So upgrade this connection to WebSocket, and then there's some key exchange in former versions of the specification that key was sent after the actual headers
52:41
without a content length header. So this kind of freaked out some of the implementations. Now it's part of a specific header. Well, and then the server just answers with HTTP 101, meaning in that case switch protocols, and then we switch over to WebSockets. And from then on we have a connection
53:02
that has been established, and both the client and the server can communicate over that connection in real time. What does that mean for us from a JavaScript point of view? Because the focus today is on JavaScript, as I mentioned. The answer is no problem. No problem means the following thing.
53:21
We have a new JavaScript object called WebSocket, and we just have to provide the URL of the WebSocket service. So we have a new protocol, not HTTP. We have WS for WebSockets, or if you're using TLS security, WSS, like HTTPS for HTTP, WSS for WS. Then we write the server name, maybe the port if you want.
53:43
Yeah, and then we have events. We have the open event. Once the connection has been opened, we can, for instance, send data to the server. Send. Nice. And if the server is sending something back to us, the message event is fired. But, again, similar to the messaging API,
54:02
so we have onMessage equals, well, then we get some data back. We get the message back and then can process the message. And this is really light and fast because of the superiority of the protocol, because it just leaves the connection open and this costly, slow handshake is just done once.
54:22
The only question remaining here is, now if you do that, what about the server? How do you write the server? Because the server needs to support this protocol. The server also needs to support the current version of the protocol. There are several versions of the WebSocket protocol,
54:41
and nowadays all modern browsers support the latest version and some of them also support older versions, but during the development of the WebSocket standard, this has been an issue. This has been a great issue. So nowadays, no problem. It works really well. You just have to decide what you do in the server, and I just want to give you two brief options
55:01
of what you could do. So if you're completely sold to JavaScript, then it might make sense to use JavaScript on the server as well. Just that you don't have to copy efforts, but maybe if you have some client-side validation rules that you would also like to run on the server, then maybe you could use one of these other techniques. And, of course, poster child of the month is Node.js,
55:23
and with Node.js you have a WebSocket module. And I'd just like to show you briefly, that's why I put code on the slides, how easy that would be done here. So you have a WebSocket server module. It's the first line. Then you instruct a web server to listen on a specific port. Then you create a WebSocket server on top of the web server,
55:42
and then you just wait for a request coming in. Well, basically that's it. You accept the connection, and then once a message gets in, you can reply with anything else. So this is basically how you would do that with Node.js if you want to go the Node.js route. If you want to go the Node.js route,
56:01
but also would like to take into account that older browsers might want to connect to your service, to your website again, you might use something like Socket.IO. So Socket.IO kind of leverages both the client and the server, makes sure that they speak the same version
56:20
of the WebSockets protocol, and it's poorly filled. So you have an ancient browser. Well, okay, then we have long polling with an iframe, for instance, or we use service at the event, if it's not an IE, but another browser which doesn't happen to support WebSockets, or a recent enough version number of WebSockets. So Socket.IO would be a nice idea.
56:41
On the server, you just load Socket.IO and tell it to listen on a specific port, and on the client you get another JavaScript API, which kind of does the same thing. So, really simple. Now, given this is a Microsoft conference, or a conference which has a focus on Microsoft technologies, of course I cannot end this talk
57:01
without at least briefly mentioning SignalR, because SignalR is ASP.NET's, and Microsoft's, well, responds to all the demand for high-performance communication, also for WebSocket support, and it basically does the same thing. So we have a server component,
57:21
which can accept WebSocket's communication calls, but can also fall back to some of the other techniques we've seen today, and also has a client-side aspect, a client-side library, which does the same thing. So you have one API on the client and one on the server, and then the API, or the code behind the API,
57:42
just tries to find out for you which actual protocol to use, and you just take care about the actual data you are sending, but not the way you are sending the data, because that's taking care of the library. So, basically, I think that's the best you can do, at least as long as not all browsers have uniform WebSocket support.
58:02
If you want to try out SignalR, there have been one or two SignalR talks, actually, at that conference, unfortunately before this talk. So, otherwise, I would have given a more thorough introduction to SignalR today, but since we're on the last conference day, it probably wouldn't make that much sense. If you want to try out SignalR, the best thing I think you can do is
58:21
don't do Hello World. Hello World is boring. Install a NuGet package, microsoft-aspnet-signalr.sample. And I've done this right before the talk, and what you get is this. You get a project, and it installs jQuery and stuff, and in the project, you also get a readme,
58:41
and that readme instructs you to basically create one new file, because you need a new owin startup class, called it startup. I didn't change anything in the project, right? And then you have to copy that line into the constructor, or into the configuration method of that constructor.
59:01
And what you've done is you can compile, and then you go to slash-signalr.sample, and then I think it's stock ticker HTML. Yeah. Stock ticker HTML. And what this does is it's just a demo
59:20
which leverages the technology using web app sockets, so let's just, for good measure, let's just open maybe two browser instances with the same page. And now once I click open market, this kind of simulates a stock market, right? I did open the market,
59:41
and now you see that both browser windows seem to be synchronized. I mean, these are different browsers, right? This would not be possible with regular HTTP calls, right? So this is really high-performance stuff going on in the background, and you see really that they are practically synchronized, right? And this high-performance can only be done with web sockets. If I would go...
01:00:00
Back to, let's say IE6 here, it would still work. Maybe it wouldn't look as pretty. I don't know if IE6 has background colors for tables. No, of course it doesn't. Just kidding. OK. So that's basically it. The slide deck also contains a kind of decision chart, which sums everything up I mentioned. What can do across domain, where do we have access to return data, what has high performance, et cetera, et cetera.
01:00:20
The most smiley's are in the web socket row. But all the other rows, of course, are convenient enough as well. All right. So far, that's from me. Hope you had some fun and insights about JavaScript and HTML5 communication. I can just recommend you stay in this very room after a short break, because there will be more JavaScript content about error handling, which I'm really looking
01:00:42
forward to as well, by Todd. And if there are any questions, I'll be here. And apart from that, hope you enjoyed the conference. Hope to see you all either back next year or at the London show in December. And well, have a great remaining day at the conference and have a safe travels back home. Thank you very much.
01:01:00
Thank you.