Home > Article > Web Front-end > HTML5 new mechanism: postMessage implements secure cross-domain communication (code)
The content of this article is about the new mechanism of HTML5: postMessage realizes secure cross-domain communication (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
HTML5 provides a new mechanism for PostMessage implementation Secure cross-source communication. Syntax
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow: a reference to other windows, such as the contentWindow property of IFRAME, executed,
returned by window.open Window object. message: data to be sent to other windows. targetOrigin:
Use the origin attribute of the window to specify which windows can receive message events. Its value can be the character "*" (indicating unlimited) or a URL transfer :
is a string of Transferable objects delivered at the same time as the message. The ownership of these objects will be transferred to the receiver of the message, and the ownership will no longer be retained after sending.
element.addEventListener(event,fn,useCaption); Three parameters event event such as
click mouseenter mouseleave callback function useCaption
is used to describe whether it is bubbling or capturing. The default value is false, which means bubble delivery. When the value is true, it is captured and passed.
Main interface main.html
nbsp;html> <meta> <meta> <meta> <title>跨域数据访问</title> <script> window.addEventListener('message',function(e){ console.log("e--->",e); const data = e.data; document.getElementById('main1').style.backgroundColor=e.data; },false) </script> <p> 我是主界面,等待接收iframe的传递 </p> <p> iframe <iframe></iframe> </p>
nbsp;html> <meta> <meta> <meta> <title>Document</title> <style> html,body{ height:100%; margin:0px; } </style> <p> 点击改变颜色 </p> <script> function changeColor(){ var frame = document.getElementById('frame'); var color=frame.style.backgroundColor; if(color=='rgb(204, 102, 0)'){ color='rgb(204, 204, 0)'; }else{ color='rgb(204,102,0)'; } console.log("frame===>",frame); console.log("color",color); frame.style.backgroundColor=color; window.parent.postMessage(color,'*'); } </script>
Related recommendations:
postMessage handles iframe cross-domain issues_html/css_WEB-ITnose
How to use postMessage in H5 to transfer data between two web pages
The above is the detailed content of HTML5 new mechanism: postMessage implements secure cross-domain communication (code). For more information, please follow other related articles on the PHP Chinese website!