Get the App
SLTechnology News&Howtos  ›  Development  › 

The usage of postMessage in html5 Cross-domain Communication

Shulou Source: shulou.com Published: 2022-06-03 07:48:50 11月15日 Update

This article introduces the use of postMessage in html5 cross-domain communication. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

PostMessagePortal.html page code

The code is as follows:

Title

Var targetOrigin = "http://22527.vhost20.boxcdn.cn";

Var defaultTitle = "Portal"

Var notificationTimer = null

Function messageHandler (e) {

If (e.origin = = targetOrigin) {

Notify (e.data)

} else {

/ / ignore messages from other origins

}

}

Function sendString (s) {

Document.getElementById ("widget") .contentWindow.postMessage (s, targetOrigin)

}

Function notify (message) {

StopBlinking ()

BlinkTitle (message, defaultTitle)

}

Function stopBlinking () {

If (notificationTimer! = = null) {

ClearTimeout (notificationTimer)

}

Document.title = defaultTitle

}

Function blinkTitle (M1, m2) {

Document.title = M1

NotificationTimer = setTimeout (blinkTitle, 1000, m2, M1)

}

Function sendStatus () {

Var statusText = document.getElementById ("statusText") .value

SendString (statusText)

}

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)

Cross-domain communication

Convey the message:

Confirm

Stop the title flashing

Code for the postMessageWidget.html page

The code is as follows:

Title

Var targetOrigin = "http://www.weixiu0376.cn";

/ / TODO whitelist array

Function messageHandler (e) {

If (e.origin = = "http://www.weixiu0376.cn") {

Document.getElementById ("status") .textContent = e.data

} else {

/ / ignore messages from other origins

}

}

Function sendString (s) {

Window.top.postMessage (s, targetOrigin)

}

Function loadDemo () {

Document.getElementById ("actionButton") .addEventListener ("click"

Function () {

Var messageText = document.getElementById ("messageText") .value

SendString (messageText)

}, true)

}

Window.addEventListener ("load", loadDemo, true)

Window.addEventListener ("message", messageHandler, true)

Display received information:

Send a message

So much for sharing the usage of postMessage in html5 cross-domain communication. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Code newsletter title information content more pages help good interest guys buddies articles messages knowledge articles references Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Information Apple macOS Xiaomi