Learn about the API for HTML5 and "she" (ii)

Source: Internet
Author: User
Tags dropfile

  Communication API 

Cross document Messaging (across documents message communication)

PostMessage API Origin Security (source Safe)

ChatFrame.contentWindow.postMessage (' Hello ', ' http://www.a.com/'); Window.addeventlistener (' message '), Messagehandler,true); function MessageHandler (e) {switch (e.origin) {case ' http://www.a.com/'://Process Message ProcessMessage ( E.data); break;defaule://message Source unrecognized//Ignore message}}//message event is a DOM event that has data and origin (source) attributes. The Data property is the actual message passed by the Sender//origin property is the sending source

  

Determine if the browser supports PostMessage apiif (typeof window.postmessage = = = ' undefined ') {//does not support postmessage}//send message window.postmessage ( ' Hello ', ' http://www.a.com/'); ChatFrame.contentWindow.postMessage (' Hello ', ' http://www.a.com/');//Monitor Var Originwhitelist = [' http://www.a.com/', ' http://www.b.com/', ' http://www.c.com/'];function Checkwhitelist (origin) { for (var i = 0, n = originwhitelist.length; i < n; i++) {if (origin = = = Originwhitelist[i]) return true; return false;} function MessageHandler (e) {if (Checkwhitelist (E.origin)) {//Process message ProcessMessage (e.data);} else{//Ignore Message}}

The Messageevent interface defined by HTML5 is also part of the HTML5 WebSockets and HTML5 Web workers.

The API used to receive messages in the HTML5 communication function is consistent with the Messageevent interface.

   XMLHttpRequest Level 2

     cross-Origin xmlhttprequests

Cross-origin HTTP requests include an Origin header that provides the server with source information for HTTP requests.

Building a Web application based on non-Origin services

  

Progress Event (Progress events)

Detects if the browser supports XMLHttpRequest level 2var XHR = new XMLHttpRequest (); if (typeof xhr.withcredentials = = = ' undefined ') {// Support for cross Origin xmlhttprequest}else{//does not support}//using progress events xhr.onprogress = function (e) {if (e.lengthcomputable) {var ratio = e.loaded/e.total;//processing Progress Information}}xhr.upload.onprogress = function (e) {if (e.lengthcomputable) {var ratio = E.loaded/e.total ;//processing progress Information}}xhr.onload = function (e) {//Complete Finished}xhr.onerror = function (e) {///Error error}//Cross-origin request Xhr.open (' GET ', ' http:// www.a.com/', true); Xhr.send ();

framebusting

Framebusting technology guarantees that some content is not loaded into the IFRAME if (window!== window.top) {window.top.location = location;} var framebusttimer;var timeout = 3000;if (window!== window.top) {Framebusttimer = SetTimeout (function () { Window.top.location = location;},timeout);} Window.addeventlistener (' message ', function (e) {switch (e.origin) {case trustedframer:cleartimeout (Framebusttimer); Break;}},true);

WebSockets API

WebSockets defines a full-duplex communication channel that communicates through a socket on the web.

Previous live web Apps: client Polling , server Push

Commet: The server proactively pushes data to the client asynchronously.

Polling: The browser sends HTTP requests periodically and receives responses at any time.

Long polling: The browser sends a request to the server, and the server keeps it open for a period of time.

  In order to establish websocket communication, the client and server upgrade the HTTP protocol to the WEBSOCKET protocol at the initial connection.

Once the connection is successful, websocket messages can be sent back and forth between the client and the server in full-duplex communication mode.

  

Detects if the browser supports websocketif (window. WebSocket) {//support websocket}else{//does not support}//websocket connection (ws://)//Secure WebSocket connection (wss://) var url = ' ws://www.a.com:8080/ WebSocket '; var w = new WebSocket (URL); w.onopen = function (e) {//Open send message//var a = new Uint8array ([8,6,5,4,3,2,1]);//w.send ( A.buffer); W.send (' Hello ');} W.binarytype = ' Arraybuffer '; w.onmessage = function (e) {//e.data}w.onclose = function (e) {//Close}w.onerror = function (e) {/ Error

  Forms API

  New input controls

    • Email
    • Url
    • Number
    • Range
    • Date pickers (date, month, week, Time, DateTime, datetime-local)
    • Search
    • Color

  New functions and features

   the new form property :

    • AutoComplete
    • Novalidate

  the new input property :

    • AutoComplete
    • Autofocus
    • Form
    • Form overrides (FormAction, Formenctype, FormMethod, Formnovalidate, Formtarget)
    • Height and width
    • List
    • MIN, Max and step
    • Multiple
    • Pattern (regexp)
    • Placeholder
    • Required

Drag and Drop

  Start drag and drop: Click and drag the mouse pointer, drag the item or area called the drag source (drag source), release the mouse pointer to complete the operation, the item reached or the target area is called the drop target .  

    Drag-and-drop events

dragstart//start dragging an element in the page (call set data type on the drag source DataTransfer setData) Drag//Drag a continuous event (called on a drag source) dragenter//Drag a new element into the page ( Called on a new element) dragleave//when dragged away from the element that triggered the DragEnter event (called on a new element) when the dragover//is moved to an element when it is on (the target call of the stay) drop//when the mouse is released, it is called on the target that is currently stuck (processing the data DataTransfer getData) dragend//triggered on a drag source, indicating that the drag is complete

    Set elements to drag

1. Set the element to drag and drop draggable= "true" 2. What to drag-ondragstart  setData () 3. Where to place-ondragover4. Place-OnDrop  getData () function DragStart (e) {// e.effectallowed = ' copy '; E.datatransfer.setdata (' text ', e.target.textcontent);//e.datatransfer.setdata (' Text ', e.target.id);} function DragOver (e) {e.stopporpagation (); E.preventdefault (); return false;} function Drop (e) {e.stopporpagation (); E.preventdefault (); var data = E.datatransfer.getdata ("text");//data.. return false;}

Transmission and control

The datatransfer object is used to get and set the time of placement data

DataTransfer properties and methods of the object: SetData (format,data)//called in ondragstart, registers a transport item in a MIME-type format getdata (format)//Gets the registered data entry for the specified type types/ /returns all the currently registered formats as an array items//Returns a list of all items and their associated formats files//returns all file associated with cleardata ()//without parameters clears all registered data, giving the format parameter only clear specific registration data setdragimage (element,x,y)//Use an existing image element as a drag image addelement (elemnet)//provide a page element and act as a drag feedback effectallowed//Set an action to be selected (None,copy, Copylink,copymove,link,linkmove,mouv,all) DropEffect//determines which type of current operation or enforces some type of operation

drag and drop files

The file API can read files asynchronously in a Web page, upload files to the server and track upload status, and convert files to page elements.

DataTransfer.files:name//filename with extension full name type//file MIME type size size in bytes lastmodifieddate//timestamp of last modified file content

Dragging and dropping files outside the browser does not trigger the drag-and-drop source's Dragstart,drag,dragend event, because the drag-and-drop source is not an element within the browser Web, but a system file.

When you drag and drop system files, you can bind the Dragenter,dragover,dragleave,drop event to a drop zone in the browser web.

var dropfile = function (opts) {This.filearea = document.getElementById (opts.filearea); This.textarea = document.getElementById (opts.textarea); This.imagearea = document.getElementById (Opts.imagearea); This.init ();}; Dropfile.prototype = {init:function () {This.textArea.innerHTML = ' drag and drop file area '; This.bind ();},bind:function () {var _this = This;this.filearea.addeventlistener (' DragEnter ', function (e) {_this.dragenter (e);},false); This.fileArea.addEventListener (' DragOver ', function (e) {_this.dragover (e);},false); This.fileArea.addEventListener (' DragLeave ', function (e) {_this.dragleave (e);},false); This.fileArea.addEventListener (' Drop ', function (e) {_this.drop (e)},false);},dragenter:function (e) {var files = E.datatransfer.files;if (files) {This.textArea.innerHTML = ' dragged ' + files.length + ' files ';} else{this.textarea.innerhtml = ' no dragged file ';} E.stoppropagation (); E.preventdefault (); return False;},dragover:function (e) {e.stoppropagation (); E.preventDefault (); return False;},dragleave:function (e) {This.textArea.innerHTML = ' drag and drop fileRegion ';},drop:function (e) {e.stoppropagation (); E.preventdefault (); var files = E.datatransfer.files;this.readfileinfo ( files); This.readfilebyimage (Files),},readfilebyimage:function (files) {var _this = this;[]. Foreach.call (files,function (file) {if (!!         File.type.match (/image/)) {var reader = new FileReader (); Reader.readasdataurl (file);         reader.onload = function (e) {             _this.imagearea.innerhtml + = '  '; nbsp;           }; }            }); },readfileinfo:function (Files) {var message = ' <ol> '; []. Foreach.call (files,function (file) {message + = ' <li> '; message + = ' file name: ' + file.name + '
'; message + = ' File type: ' + File.type + '
'; message + = ' File size: ' + file.size + '
'; message + = ' File Last modified: ' + File.lastmodifieddate + '
'; message + = ' </li> ';}); Message + = ' </ol> '; this.textArea.innerHTML = Message;}} Window.onload = function () {new Dropfile ({filearea: ' Filearea ', TextArea: ' TextArea ', Imagearea: ' Imagearea '});}

  

Learn about the API for HTML5 and "she" (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.