does unhandled postMessage leak memory?
javascript, memory-leaks, postmessage
Solution
`postMessage` initiates a `MessageEvent` on the target, which is not more special than a regular `onload` event.
The event itself does not cause any memory leaks. You can create memory leaks by introducing unwanted closures, but that also applies to regular functions:
window.addEventListener('message', messageHandler, false);
function messageHandler(event) {
var img = new Image();
img.onload = function() {
document.body.appendChild(img);
};
img.src = event.data.some.property.deep.ly.nested.obj.bad.coding.style.src;
}
What's the problem? The image's `onload` handler inserts the picture in the document when it's loaded. However, because of the closure, the `event` object cannot be freed, and the big `event.data` object will still occupy memory.
Another way to introduce a memory leak (same-origin only) is to save the value of `event.source` (preventing the frame's view from being GC'd when the frame is removed):
var stupidity = [];
window.onmessage = function(event) {
stupidity.push(event.source);
};
Problem
I have a page that may work as a standalone webpage or within a special "watchdog frame" to which it would be sending messages periodically using `window.top.postMessage('message', '*');` The problem is if the page is loaded as standalone webpage, there will be nothing to capture these messages. Users can be expected to hold that page open for hours or even days at a time. Do these uncaught messages just vanish without a trace, or do they get queued or something like that, leaking the memory?