2

I need help with the window.postMessage method. I'm trying to post a message to an iframe from the parent window.

The iframe's name and ID is myFrame, and I have tried the following code, with no avail:

document.getElementById('myFrame').contentWindow.postMessage('Hello','*')
6
  • 1
    Are the pages on the same domain? Otherwise you're going to be running into XSS security issues and quite likely the reason it's not working. Commented Jan 16, 2011 at 16:39
  • @kieran I was looking for a cross-domain communication and I found this as the best way after almost 2 days of googling :- developer.mozilla.org/en/dom/window.postmessage Commented Jan 16, 2011 at 16:47
  • What error did it give you? Just "it's not working" is not specific enough. Commented Jan 16, 2011 at 16:58
  • @Thai no error is being produced in the console, it's left blank!! Commented Jan 16, 2011 at 17:04
  • 2
    A bit OT, but there are some very good ways of doing cross domain/frame communication that doesn't use window.postmessage, try to look here for inspiration: softwareas.com/cross-domain-communication-with-iframes Commented Jan 16, 2011 at 18:46

1 Answer 1

1

Take a step back and debug.

  1. What does document.getElementById('myIframe') give you?
  2. What does document.getElementById('myIframe').contentWindow give you?
  3. Do you have a global method named postMessage in the iframe?
  4. Is the iframe domain the same as the initial page? It has to be.
  5. Does the browser throw any errors in the console?
Sign up to request clarification or add additional context in comments.

2 Comments

The iframe does not have to be on the same domain for window.postMessage.
Mattio is correct, the iframe does not have to be on the same domain. I've run into this problem as well and it seems the problem lies in that document.getElementById('myFrame').contentWindow returns undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.