onmessage event
The onmessage
event activates a <script>
when a message is received from another window or iframe. It is often used with the postMessage API to enable cross-origin communication.
Syntax
In HTML
<element onmessage="myScript">
In JS
object.onmessage = function(){myScript};
addEventListener()
function is used. In JavaScript, the
object.addEventListener("message", myScript);
Example
<h1 id="myH1"></h1>
<div id="myDIV"></div>
<p><strong>Note:</strong> Server-Sent Events are not supported in Internet Explorer.</p>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("/html/demo_sse.php");
source.onopen = function() {
document.getElementById("myH1").innerHTML = "Getting server updates";
};
source.onmessage = function(event) {
document.getElementById("myDIV").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("myDIV").innerHTML = "Sorry, your browser does not support server-sent events...";
}
Values
Conclusion
The onmessage
event is essential for handling messages sent between different windows or iframes. It is frequently used with the postMessage API for secure cross-origin communication. This event enables real-time data exchange between different parts of a web application.
Navigation
HTML navigation event attributes handle user interactions related to page navigation, such as loading, leaving, or changing the URL.
onpagehide
The onpagehide event is triggered when the user is leaving a webpage. This can happen through various actions, such as clicking a link or closing the browser tab.