I need to listen to a message
event that will have a data
attribute and depending on this attribute do different actions.
window.addEventListener("message", m => { if m.data === "success" { console.log("Success!") } else { console.log("Failure!") } });
Now, I want to test this with a button by dispatching such an event. However, I can only find the detail attribute, but not how to set the data attribute:
<button id="messageButton">Send Message</button>
and
messageButton.onclick = function () { messageButton.dispatchEvent(new CustomEvent("message", { bubbles: true, detail: "success" })) }
How can I send with the data
attribute instead of the detail
attribute?
Advertisement
Answer
If you’re testing a message event, you probably want MessageEvent
rather than CustomEvent
. MessageEvent
‘s constructor accepts an “init” object with a data
property:
function sendMessage(data) { const event = new MessageEvent("message", { data }); window.dispatchEvent(event); }
Example:
window.addEventListener("message", m => { if (m.data === "success") { console.log("Success!"); } else { console.log("Failure!"); } }); function sendMessage(data) { const event = new MessageEvent("message", { data }); window.dispatchEvent(event); } document.getElementById("btnSuccess").addEventListener("click", function() { sendMessage("success"); }); document.getElementById("btnFailure").addEventListener("click", function() { sendMessage("failure"); });
<button id="btnSuccess" type="button">Send 'success' Message</button> <button id="btnFailure" type="button">Send 'failure' Message</button>
But if you want to use CustomEvent
, you’d create the event object, then add the property to it:
function sendMessage(data) { const event = new CustomEvent("message", { bubbles: true }); event.data = data; window.dispatchEvent(event); }
Example:
window.addEventListener("message", m => { if (m.data === "success") { console.log("Success!"); } else { console.log("Failure!"); } }); function sendMessage(data) { const event = new CustomEvent("message", { bubbles: true }); event.data = data; window.dispatchEvent(event); } document.getElementById("btnSuccess").addEventListener("click", function() { sendMessage("success"); }); document.getElementById("btnFailure").addEventListener("click", function() { sendMessage("failure"); });
<button id="btnSuccess" type="button">Send 'success' Message</button> <button id="btnFailure" type="button">Send 'failure' Message</button>