---
title: "Cross-Window Messaging"
description: "Cross-origin/window communication is possible with the HTML5 API window.postMessage. Practical notes and code examples on."
url: "https://h3manth.com/scribe/cross-window-messaging/"
canonical_url: "https://h3manth.com/scribe/cross-window-messaging/"
markdown_url: "https://h3manth.com/scribe/blog/cross-window-messaging.md"
publishDate: "2012-07-22T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["javascript","html5"]
word_count: 234
reading_time_minutes: 2
x_markdown_tokens: 542
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Cross-Window Messaging

> Cross-origin/window communication is possible with the HTML5 API window.postMessage. Practical notes and code examples on.

Cross-origin/window communication is possible with the HTML5 API `window.postMessage`.

Scripts on different pages are only allowed to access each other only if the pages which executed them are at locations with the same protocol and host, but `window.postMessage` provides a controlled mechanism to circumvent this restriction in a way which is secure when properly used.

Before diving into some theory, have a look at the [demo](http://h3manth.com/demo/postMessage/)

The MessageEvent interface is as below:

```javascript
interface MessageEvent : Event {
  readonly attribute any data;
  readonly attribute DOMString origin;
  readonly attribute DOMString lastEventId;
  readonly attribute WindowProxy source;
  readonly attribute MessagePortArray ports;
  void initMessageEvent(
    in DOMString typeArg, 
    in boolean canBubbleArg, 
    in boolean cancelableArg, 
    in any dataArg, 
    in DOMString originArg, 
    in DOMString lastEventIdArg, 
    in WindowProxy sourceArg, 
    in MessagePortArray portsArg
  );
};
```

`data` and `origin` are of the prime most importance here - the data gives the message that is sent via `postMessage` and origin gives the domain origin.

One can easily check and return if the event origin is not as expected:

```javascript
if (event.origin !== "http://h3manth.com") {
    return;
}
```

If you check out the source of the demo:

```javascript
var frame = document.getElementById("if").contentWindow;
frame.onmessage = function(e) {
    frame.document.body.innerHTML += "Message from " + e.origin + " " + e.data;
};

document.getElementById("send").onclick = function() {
    var msg = document.getElementById("res").innerHTML;
    frame.postMessage(msg, "http://h3manth.com/blog");
};
```

Notice that `postMessage` is not from the same page as the demo is in.
