The cross-origin threshold of HTML5 communication APIS is no longer high, and data push is no longer a dream.

Source: Internet
Author: User

Comments: Two new communication-related APIs are added for HTML5, including cross-document message transmission and WEB Sockets API. The cross-document message transmission function allows message transmission on different webpage documents and ports (cross-origin. The web sockets api allows the client and server to transmit data through the socket port, so that data push technology can be used.Preface

Two APIs related to communication are added to HTML5: Cross-document message transmission and WEB Sockets APIs,

The cross-document message transmission function allows you to transmit messages on different webpage documents and ports (in cross-domain situations.

The web sockets api allows the client and server to transmit data through the socket port, so that data push technology can be used.

Cross-document message transmission

Previously, it would take a lot of effort to obtain cross-origin information. Now, you only need to retrieve the window object instance where the webpage is located and change it to implement mutual communication.

First, you need to listen on the window objects of messages sent from other windows:

window.addevntListener('message', function () {}, false)

Use the postMessage method of a windows Object to send messages to other windows:

OtherWindow. postMessage (message, targetOrigin) the first parameter is to send text, or it can be the js object (json). The second parameter is the URL of the receiving message Object window. Wildcards can be used.

Simple Example:

The Code is as follows:
Post information
<! DOCTYPE html>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>
<Script src = "../jquery-1.7.1.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
Window. addEventListener ('message', function (ev ){
// Check the message source
Messages ('{msg_box'{.html (ev. origin + 'sent message:' + ev. data );
}, False );

$ ('# Send'). click (function (){
Var frame = window. frames [0];
Frame. postMessage ($ ('# msg '). val (), 'HTTP: // localhost: 3317/html5% E4 % B8 % 8Ecss3/06% E9 % 80% 9A % E8 % AE % AFapi/02.htm ');
});
});

</Script>
</Head>
<Body>
<Input type = "text" id = "msg"/>
<Button id = "send">
Send message </button>
<Iframe src = "02.htm" width =" 400 "> </iframe>
<Div id = "msg_box">
</Div>
</Body>
</Html>

Based on the above, we make some modifications. We provide a high-width button on the Child page to tell the parent window how to change the iframe high-width:

The Code is as follows:
Parent code
<! DOCTYPE html>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>
<Script src = "../jquery-1.7.1.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
Window. addEventListener ('message', function (ev ){
// Check the message source
Messages ('{msg_box'{.html (ev. origin + 'sent message:' + ev. data );

Var w_h = ev. data;
// No format check is performed
(('{F'}.css ('width', w_h.split (',') [0] + 'px ');
(('{F'}.css ('height', w_h.split (',') [1] + 'px ');

}, False );

Function p (){
Var frame = window. frames [0];
Frame. postMessage ($ ('# msg '). val (), 'HTTP: // localhost: 3317/html5% E4 % B8 % 8Ecss3/06% E9 % 80% 9A % E8 % AE % AFapi/02.htm ');
}
$ ('# Send'). click (function (){
P ();
});
SetTimeout (p, 200 );

});

</Script>
</Head>
<Body>
<Input type = "text" id = "msg"/>
<Button id = "send">
Send message </button>
<Iframe src = "02.htm" width =" 400 "id =" f "> </iframe>
<Div id = "msg_box">
</Div>
</Body>
</Html>


The Code is as follows:
Sub-Layer Code
<! DOCTYPE html>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>
<Script src = "../jquery-1.7.1.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
Var url = '';
Var source = '';
Window. addEventListener ('message', function (ev ){
// Source verification is required here
If (ev. origin ){}
('{Msg'{.html (ev. origin + 'sent message:' + ev. data );
Url = ev. origin;
Source = ev. source;
// Ev. source. postMessage ('here is: '+ this. location, ev. origin );
});

$ ('# Send'). click (function (){
Source. postMessage ($ ('# w_h'). val (), url );
});
});
</Script>
</Head>
<Body>
<Div id = 'msg '>
</Div>
<Input type = "text" id = "w_h"/>
<Button id = "send">
Change the outer height </button>
</Body>
</Html>

Finally, we cut the e image:

This api can be used more flexibly. We can pass the function name or something and we can do a lot of things anyway.

Web sockets communication

Web sockets is a non-HTTP Communication Mechanism provided by html5.

He has implemented smart communication technologies such as server data push, which is not easily implemented by http, so he has received high attention.

You can use the web sockes api to establish a non-HTTP bidirectional connection between the server and the client. This connection is real-time and permanent, unless it is explicitly closed.

This means that when the server wants to send data to the client, it can push the data to the client's browser immediately without re-establishing the connection.

As long as the client has an opened socket and a connection is established with the server, the server can push the data to this socket. The server no longer needs to poll client requests, making it passive.

Web sockets api

The Code is as follows:
Var webSocket = new WebSocket ('ws: // localhost: 8005/socket ');
The url must use ws or wss (encrypted) as the header. After this url is set, you can obtain it again by accessing the url of the websocket object in javascript script.
After a connection is established, two-way communication is enabled. You can use the send method of the websocket object to add json data to transmit any form of data to the server: </p> <p> webSocket. send (msg );
The onmessage event is used to receive data transmitted by the server:
WebSocket. onmessage = function (e ){
Var data = e. data;
};
Use the onopern event to listen to the socket open event:
WebSocket. onopen = function (e ){};
Use onclose to listen to socket close events:
WebSocket. onclose = function (e ){};
Use webSocket. close () to close the socket connection. </p> <p> use the readyState attribute to get the status of the websocket object:
CONNECTION 0 is connecting
OPEN 1 is connected
CLOSING 2 is shutting down
CLOSE 2 is closed

PS: Because I will not configure socket-related server blocks, I cannot perform tests for the time being. This problem will be solved when I study it again.

The entire code is still very simple:

The Code is as follows:
// Create a Socket instance
Var socket = new WebSocket ('ws: // localhost: 100'); </p> <p> // open the Socket
Socket. onopen = function (event) {</p> <p> // send an initialization message
Socket. send ('I am the client and I \' m listening! '); </P> <p> // listens to messages.
Socket. onmessage = function (event ){
Console. log ('client received ed a message', event );
}; </P> <p> // listener for Socket disabling
Socket. onclose = function (event ){
Console. log ('client notified socket has closed ', event );
}; </P> <p> // close the Socket ....
// Socket. close ()
};


Related Article

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.