Pushing the Web: Interesting things to Know
-
Upload
nu-the-open-security-community -
Category
Education
-
view
3.509 -
download
1
Transcript of Pushing the Web: Interesting things to Know
Pushing the web: Interesting things to know about upcoming web standards
By Shwetank Dixit, Opera Software
about meWeb Evangelist, Opera Developer Relations Team
Member, W3C Mobile Web for Social Development Group
Member, W3C Web Education Community Group
twitter.com/shwetankemail: [email protected]
Front-end development - a lot of learn!
We’ll focus on a few things
We’ll focus on a few thingsHTML5 and friends
Same Origin PolicyOur story begins from here...
Same Origin Policy1. Let /A/ be the first origin being compared, and let /B/ be the second origin being compared.
2. If either /A/ or /B/ is not a scheme/host/port tuple, return an implementation-defined value.
3. If /A/ and /B/ have scheme components that are not identical, return false.
4. If /A/ and /B/ have host components that are not identical, return false.
5. If /A/ and /B/ have port components that are not identical, return false.
6. Return true.
Same Origin PolicyShould have the same...
Scheme / Host / Port
Same Origin PolicyThese will NOT match, and considered separate origins
http://www.example.orghttps://www.example.org
Same Origin PolicyThese will NOT match, and considered separate origins
http://www.example.orghttp://xyz.example.org
Same Origin PolicyThese will NOT match, and considered separate origins
http://www.example.orghttp://www.example.org:1337
Same Origin PolicyThese WILL match, and are considered the same origin
http://www.example.org/abc/http://www.example.org/xyz/
Storage: Web Storage
The problem with cookiesUnreliableNo programmatic APIs to manipulate itNot structured
Most of important of all ...Small file size, so very limited data can be stored.
Web StorageSession Storage and Local Storage
localStorage.setItem(yourkey, yourvalue); // Store the value
var item = localStorage.getItem(yourkey); // Retrieve the value and assign it to a variable
Example of using Web Storage to store and retrieve values in the browser’s local storageWith this, even if you close the browser and re-open the page again, the values should still load properly.
You can store images (and more) with localStorage
....BUT DON”T.
Automatically save entered form info locallyin case page crashes or closes, person can resume from where he left off
<textarea id="draft" rows="10" cols="30"></textarea>
...
...
function saveMessage(){
� var message = document.getElementById("draft");
� localStorage.setItem("message", message.value)
}
setInterval(saveMessage, 500);
STORE USER DATA OFFLINE PERIODICALLY
Or...You could save only when you detect a new keystroke (or a minimum number of them)
Gotcha Two tabs updating the same value
Storage eventsKnow if some other page has changed the value or not
addEventListener('storage', function(event){
� if (e.oldValue){
� alert('changed from \''+event.oldValue+'\' to \''+event.newValue+'\'');
� }
}, false);
GET NEW VALUE IF ITS BEEN CHANGED IN PARALLEL TAB
GotchaUsing a free hosting service - Don’t use local storage with it if they store users accounts on different directories.
e.g, freehosting.com/user1 and freehosting.com/user2
Cross Origin Resource Sharing (CORS)
Whats CORS?
CORS is a system of headers and rules that allow browsers and servers to communicate whether or not a given origin is allowed access to a resource stored on another.
Access-Control-Allow-Origin
Header to Let the referrer know whether it is allowed to use the target resource.
Access-Control-Allow-Origin
Access-Control-Allow-Origin: nullAccess-Control-Allow-Origin: *Access-Control-Allow-Origin: http://foo.example
Cross Domain XHR
var xhr = new XMLHttpRequest();var onLoadHandler = function(event) { /* do something with the response */}xhr.open('GET','http://url-of-other.server/and/path/to/script');
Capture JS errors ... with JS
window.onerror
window.onerror
Error MessageLine NumberFile URL in question
window.onerror
window.onerror = function(message, url, linenumber) {
alert("JavaScript error: " + message + " on line " + linenumber + " for " + url);
}
What could you do with it?
Better looking error messages.
Log errors in a flat file or DB.
WebSockets
Previous techniques
Continuous PollingLong Polling
WebSockets
Built Over HTTPFull DuplexBi-Directional
HTTP Server ‘upgrades’ to a WebSocket server
The initiating handshake from the client should look like this:
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
And on the server
HTTP/1.1 101 Switching Protocols
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat
What happens1. The client sends the Sec-WebSocket-Key string dGhlIHNhbXBsZSBub25jZQ==
2. The server appends the magic string to form the string dGhlIHNhbXBsZSBub25jZQ== 258EAFA5-E914-47DA-95CA-C5AB0DC85B11
3. Now the server generates the SHA-1 hash for this longer string, which is b37a4f2cc0624f1690f64606cf385945b2bec4ea
4. Finally, the server base64-encodes the hash string to give s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
5. And this base64-encoded value is used in the Sec-WebSocket-Accept header in the server’s response.
WebSockets APIif ('WebSocket' in window){ /* WebSocket is supported. You can proceed with your code*/} else { /*WebSockets are not supported. Try a fallback method like long-polling etc*/}
WebSockets APIvar connection = new WebSocket('ws://example.org:12345/myapp');
or wss://, which is the secure socket variant to ws:// in the same way https is to http
var connection = new WebSocket('wss://secure.example.org:67890/myapp');
Handling an open connectionconnection.onopen = function(){ /*Send a small message to the console once the connection is established */ console.log('Connection open!');}
Sending Messagesconnection.send('Hey server, whats up?');
or
var message = {'name': 'bill murray','comment': 'No one will ever believe you'};connection.send(JSON.stringify(message));
Receiving Messagesconnection.onmessage = function(e){ var server_message = e.data; console.log(server_message);}
Use Cases
Any App which wants real time updating of info
1. High performance web based games2. Sport Scores3. Social Media real time updates4. Breaking news real time updates5. Chat applications
My Websockets article on DeveloperFusionhttp://www.developerfusion.com/article/143158/an-introduction-to-websockets/
Device OrientationAccess to gyroscope, accelerometer info etc
Access gyroscope info
window.addEventListener("deviceorientation", function(event) {
// process event.alpha, event.beta and event.gamma
}, true);
Access accelerometer infowindow.addEventListener("devicemotion", function(event) {
// Process event.acceleration
}, true);
Another sneak peak
Check for accessvar options = {‘video’: true, ‘audio’: false};
if (navigator.getUserMedia){ navigator.getUserMedia(options, v_success, v_error); }
else{ not_supported(); }
Check for accessvar video_element = document.querySelector('video');......function v_success(stream){ video_element.src = stream; }
Use camera + <video> + <canvas> for new tricksvar button = document.querySelector('#button'); button.addEventListener('click',snapshot, false);......function snapshot(){ var c = document.querySelector('canvas'); var ctx = c.getContext('2d'); var cw = c.clientWidth; var ch = c.clientHeight; ctx.drawImage(video_element, 0, 0, cw, ch); }
Keep in mindWebRTC spec (containing getUserMedia) is still in flux. Not a mature standard yet.
Webkit has prefixed its version of getUserMedia.
Get it on:
Opera Labs BuildLatest Opera.NextOpera Mobile 12
Opera Dragonfly
(RIGHT-CLICK ON PAGE) -> ‘INSPECT ELEMENT’
Inspect the DOM
Debug JavaScript
Network inspector
Style profiler
Tools - Color Picker
Remote debugging
Opera Mobile Emulator
Opera Mobile Emulator
Opera Mobile Emulator
The Developer Briefcase
‘Edit the Page’ extension
- YSlow!- PageRank- Firebug Lite- LiveReload- Layers- ResizeMe- GitHub Notifierand more...
Other developer extensions for Opera
HTTPS://ADDONS.OPERA.COM/EN/EXTENSIONS/CATEGORY/WEB-DEVELOPMENT
Read up on
Dev.opera.com
Cheers!More questions? Ask me now or contact me at:[email protected] or, twitter.com/shwetank