Comments: This article provides a detailed summary of the usage of postMessage for html5 cross-origin communication. If you need it, you can refer to it for help.
PostMessagePortal.html Page code
The Code is as follows:
<! DOCTYPE html>
<Title> title </title>
<Link rel = "stylesheet" href = "styles.css">
<Link rel = "icon" href = "http://apress.com/favicon.ico">
<Script> </p> <p> var targetOrigin = "http://22527.vhost20.boxcdn.cn"; </p> <p> var defaultTitle = "Portal ";
Var icationicationtimer = null; </p> <p> function messageHandler (e ){
If (e. origin = targetOrigin ){
Notify (e. data );
} Else {
// Ignore messages from other origins
}
} </P> <p> function sendString (s ){
Document. getElementById ("widget"). contentWindow. postMessage (s, targetOrigin );
} </P> <p>
Function Y (message ){
StopBlinking ();
BlinkTitle (message, defaultTitle );
} </P> <p> function stopBlinking (){
If (icationicationtimer! = Null ){
ClearTimeout (icationicationtimer );
}
Document. title = defaultTitle;
} </P> <p> function blinkTitle (m1, m2 ){
Document. title = m1;
NotificationTimer = setTimeout (blinkTitle, 1000, m2, m1)
} </P> <p> function sendStatus (){
Var statusText = document. getElementById ("statusText"). value;
SendString (statusText );
} </P> <p> function loadDemo (){
Document. getElementById ("sendButton"). addEventListener ("click", sendStatus, true );
Document. getElementById ("stopButton"). addEventListener ("click", stopBlinking, true );
SendStatus ();
}
Window. addEventListener ("load", loadDemo, true );
Window. addEventListener ("message", messageHandler, true); </p> </script> </p> Transfer Information: <input type = "text" id = "statusText" value = "Online">
<Button id = "sendButton"> OK </button>
<Iframe id = "widget" src = "http://22527.vhost20.boxcdn.cn/postMessageWidget.html"> </iframe>
<P>
<Button id = "stopButton"> stop title flashing </button>
</P>
PostMessageWidget.html Page code
The Code is as follows:
<! DOCTYPE html>
<Title> title </title>
<Link rel = "stylesheet" href = "styles.css">
<Script> </p> <p> var targetOrigin = "http://www.weixiu0376.cn "; </p> <p> // TODO whitelist array </p> <p> function messageHandler (e ){
If (e. origin = "http://www.weixiu0376.cn "){
Document. getElementById ("status"). textContent = e. data;
} Else {
// Ignore messages from other origins
}
} </P> <p> function sendString (s ){
Window. top. postMessage (s, targetOrigin );
} </P> <p> function loadDemo (){
Document. getElementById ("actionButton"). addEventListener ("click ",
Function (){
Var messageText = document. getElementById ("messageText"). value;
SendString (messageText );
}, True); </p> <p>}
Window. addEventListener ("load", loadDemo, true );
Window. addEventListener ("message", messageHandler, true); </p> </script>
<P> display receiving information: <strong id = "status"> </strong> <p>
<Div>
<Input type = "text" id = "messageText" value = "Enter the message content">
<Button id = "actionButton"> send message </button>
</Div>