search
HomeWeb Front-endH5 TutorialHTML5 communication API cross-domain threshold will no longer be high, data push is no longer a dream_html5 tutorial skills

Foreword

HTML5 adds two new APIs related to communication, cross-document message transmission and WEB Sockets API,

Cross-document message transmission function can transmit messages in different web documents and different ports (in cross-domain situations).

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

Cross-document messaging

In the past, if we wanted to obtain information across domains, it would have taken a lot of effort. Now we can communicate with each other as long as we obtain the instance of the window object where the web page is located.

First of all, if you want to receive messages from other windows, you need to monitor their window objects:

window.addevntListener(<span style="COLOR: #800000">'</span><span style="COLOR: #800000">message</span><span style="COLOR: #800000">'</span>, function () {}, <span style="COLOR: #0000ff">false</span>)

Use the postMessage method of the windows object to send messages to other windows:

<span style="COLOR: #000000">otherWindow.postMessage(message, targetOrigin)第一个参数为发送文本,也可以是js对象(json)第二个参数为接收消息对象窗口的URL,可以使用通配符</span>

Simple example:

Copy code
The code is as follows:

post information



title><br> <script src="../jquery-1.7.1.js" type="text/javascript"></script><br> <script type="text/javascript"></script> $(document).ready(function () {<br> window.addEventListener('message', function (ev) {<br> //The source of the message should be checked<br> $('#msg_box' ).html(ev.origin 'Sent message:' ev.data);<br> }, false);<br> <br> $('#send').click(function () {<br> var frame = window.frames[0];<br> frame.postMessage($('#msg').val(), 'http://localhost:3317/html5 and css3/06 communication api/02.htm') ;<br> });<br> });<br> <br> <br> <br>



Based on the above, we make a little modification. We provide height and width buttons on the sub-page to tell the parent window how to change the iframe height and width:

Copy code
The code is as follows:

Parent layer code

















Copy the code
The code is as follows:

Sub-layer code





< ;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 ' Send 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);
});
});










Finally, take a screenshot of our e:

For more flexible use, the API can be used more powerfully. We can pass function names and so on. Anyway, we can do a lot of things.

web sockets communication

Web sockets are a non-HTTP communication mechanism provided by HTML5 between the client and the server in web applications

He has realized intelligent communication technologies such as data push to the server that is not easy to implement with http, so he has received a lot of attention.

Using the web socks api, you can establish a non-HTTP two-way 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 immediately to the client's browser without re-establishing the connection.

As long as the client has an open socket and establishes a connection with the server, the server can push data to the socket. The server no longer needs to poll the client for requests, turning passive into active.

web sockets api

Copy code
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, it can be passed in the javascript script Access the url of the websocket object to re-acquire
communication. After establishing a connection, two-way communication is possible. Use the send method of the websocket object and add json data to transfer any form of data to the server:

webSocket.send(msg);
Receive data sent from the server through the onmessage event:
webSocket.onmessage = function (e) {
 var data = e.data;
} ;
Listen to the socket open event through the onopern event:
webSocket.onopen = function (e) { };
Listen to the socket close event through onclose:
webSocket.onclose = function (e) {};
Close the socket connection through the webSocket.close() method;

Get the websocket object status through the readyState attribute:
CONNECTION 0 Connecting
OPEN 1 Connected
CLOSING 2 Closing
CLOSE 2 Closed


PS: Because I don’t know how to configure the socket related to the server block, I can’t test it for the time being. This problem will be solved during secondary learning.

The whole code is still very simple:

Copy the code
The code is as follows:

// Create a Socket instance
var socket = new WebSocket('ws://localhost:8080');

//Open Socket
socket.onopen = function(event) {

//Send an initialization message
socket.send('I am the client and I'm listening!');

// Listen for messages
socket.onmessage = function(event) {
console.log('Client received a message',event);
};

// Monitor the closing of Socket
socket.onclose = function(event) {
console.log('Client notified socket has closed', event);
};

// Close Socket....
//socket.close()
};

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

H5 vs. HTML5: Clarifying the Terminology and RelationshipH5 vs. HTML5: Clarifying the Terminology and RelationshipMay 05, 2025 am 12:02 AM

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor