HTML5 window.postMessage and cross-domain example tutorial
This article mainly introduces the detailed explanationHTML5 window.postMessage and cross-domain, which are of great practical value. Friends in need can refer to it
In the previous article, we talked about The browser's same-origin policy prevents pages from different domains from accessing each other's methods and attributes. It also explains the solutions proposed to solve the cross-domain problem of the same-origin policy: subdomain proxy, JSONP, and CORS. This article will elaborate on HTML5 window.postMessage. With the postMessage API, cross-domain communication can be achieved between documents in a safe and controllable manner. Third-party JavaScript code can also communicate with external documents loaded in iframes.
HTML5 window.postMessage API
HTML5 window.postMessage is a secure, event-based messaging API.
postMessage sends a message
Call the postMessage method in the source window where the message needs to be sent to send the message.
Source window
The source window can be a global window object or the following types of windows:
iframe in the document window:
var iframe = document.getElementById('my-iframe'); var win = iframe.documentWindow;
Pop-up window opened by JavaScript:
var win = window.open();
The parent window of the current document window:
var win = window.parent;
Open the window of the current document:
var win = window.opener();
Find the source window object After that, you can call the postMessage API to send a message to the target window:
``win.postMessage('Hello', 'ttp://jhssdemo.duapp.com/');"
postMessageFunctionReceives two parameters: the first is the message to be sent, and the second is the source of the source window .
Note: The message can only be received when the source of the target window matches the source parameter value passed in the postMessage function.
Receive postMessage message
To receive the message previously sent by the source window through postMessage, you only need to register the message event in the target window and bind the event listening function. The message can be obtained in Function parameters.
window.onload = function() { var text = document.getElementById('txt'); function receiveMsg(e) { console.log("Got a message!"); console.log("nMessage: " + e.data); console.log("nOrigin: " + e.origin); // console.log("Source: " + e.source); text.innerHTML = "Got a message!<br>" + "Message: " + e.data + "<br>Origin: " + e.origin; } if (window.addEventListener) { //为窗口注册message事件,并绑定监听函数 window.addEventListener('message', receiveMsg, false); }else { window.attachEvent('message', receiveMsg); } };
message event listening function receives a parameter, an Event object instance, which has three attributes:
data sent Message
origin Send message source
source Send message window window objectReference
Explanation
You can set the second parameter of the postMessage function to *, and when sending a cross-domain message, the source of the message will be skipped. inspection.
postMessage can only send string information.
Example
Source window
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Html5 postMessage</title> <style> #otherWin { width: 600px; height: 400px; background-color: #cccccc; } </style> </head> <body> <button id="btn">open</button> <button id="send">send</button> <!-- 通过 iframe 嵌入子页面(接收消息目标窗口) --> <iframe src="http://jhssdemo.duapp.com/demo/h5_postmessage/win.html" id="otherWin"></iframe> <br/><br/> <input type="text" id="message"><input type="button" value="Send to child.com" id="sendMessage" /> <script> window.onload = function() { var btn = document.getElementById('btn'); var btn_send = document.getElementById('send'); var sendBtn = document.getElementById('sendMessage'); var win; btn.onclick = function() { //通过window.open打开接收消息目标窗口 win = window.open('http://jhssdemo.duapp.com/demo/h5_postmessage/win.html', 'popUp'); } btn_send.onclick = function() { // 通过 postMessage 向子窗口发送数据 win.postMessage('Hello', 'http://jhssdemo.duapp.com/'); } function sendIt(e){ // 通过 postMessage 向子窗口发送数据 document.getElementById("otherWin").contentWindow .postMessage( document.getElementById("message").value, "http://jhssdemo.duapp.com/"); } sendBtn.onclick = function(e) { sendIt(e); }; }; </script> </body> </html>
Target window win.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Html5 postMessage</title> <style> #txt { width: 500px; height: 300px; background-color: #cccccc; } </style> </head> <body> <h1>The New Window</h1> <p id="txt"></p> <script> window.onload = function() { var text = document.getElementById('txt'); //监听函数,接收一个参数--Event事件对象 function receiveMsg(e) { console.log("Got a message!"); console.log("nMessage: " + e.data); console.log("nOrigin: " + e.origin); text.innerHTML = "Got a message!<br>" + "Message: " + e.data + "<br>Origin: " + e.origin; } if (window.addEventListener) { //为window注册message事件并绑定监听函数 window.addEventListener('message', receiveMsg, false); }else { window.attachEvent('message', receiveMsg); } }; </script> </body> </html>
Review
Through the study of this article, I learned about using HTML5’s postMessage API to communicate between windows, and also learned that it can be used to achieve cross-domain communication; modern browsers basically support it postMessage, for some old browsers such as IE7-etc., certain alternatives can be used for data communication, such as window.name, url query characters and hash fragments, etc.
【Related Recommendations】
1. Special Recommendation:"php Programmer Toolbox" V0.1 version Download
2. Free h5 online video tutorial
##3.php.cn original html5 video tutorial
The above is the detailed content of HTML5 window.postMessage and cross-domain example tutorial. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.
