Specification 9.4.3 Message ports.
Pay careful attention to
port.close()
Disconnects the port, so that it is no longer active.
and the lack of an interface to determine if a MessagePort
is closed.
Some sample code. I ran the same code on Chromium Version 124.0.6353.0 (Developer Build) (64-bit) and Firefox 125.0a1 (2024-03-11) (64-bit), both fetched today from tip-of-tree builds. I’ll leave it to the JavaScript programmer to run the code in different JavaScript runtime environments to observe the results on the system being used.
var {
port1,
port2
} = new MessageChannel();
var messagesReceivedAfterPortClose = 1;
port1.addEventListener("message", (e) => {
console.log(e);
port1.close();
console.log("This port should be closed. This should be logged at most once!");
console.log(`Actually logged ${messagesReceivedAfterPortClose++}`);
});
port2.addEventListener("message", (e) => {
console.log(e);
});
port1.addEventListener("messageerror", (e) => {
console.log(e);
});
port2.addEventListener("messageerror", (e) => {
console.log(e);
});
port1.start();
port2.start();
port1.postMessage(1);
port2.postMessage(2);
port2.postMessage(3);
port2.postMessage(4);
port2.postMessage(5);
The question: How to determine if a MessagePort
is closed?