Proper use of javascript postMessage()

dec 9 2019, 3:08pm

postMessage() is simply the only way of 2 browser windows / iframes to communicate to each other.

Sending

	<script>
		'use strict';

		var host = 'https://smokingscript.com',
			windowTarget = //a window object;

		windowTarget.postMessage('hello receiver, this is sender!', host);
	</script>

Receiving

	<script>
		'use strict';
		
		var host = 'https://smokingscript.com';
		
		window.addEventListener('message', function(ev){
			if(ev.origin !== host)
				return;//sender not from this host, reject
			else
				//do something here with received ev.data
		}, false);
	</script>

Demo

browser windows communication with javascript postMessage() demo (on a sister site).

Reference

Window.postMessage() - Web APIs | MDN

Comments