9

I'm trying to get a value from local storage on a site loaded through an Iframe. I'm able to send a message to the site within the iframe through postMessage, but haven't figured out how to return data from the postMessage call. I've looked into promises, but haven't figured out how to get it working.

Anyone have an idea?

jck
  • 541
  • 6
  • 21
Harry Manback
  • 417
  • 1
  • 5
  • 12

1 Answers1

7

I iframe window needs to listen for the "message" event, process the message, and then send a postMessage back to the window of the messenger.

You can read about the API here: window.postMessage().

David Walsh has also written a good tutorial on how to do this.

I hope this helps!

Kyle Richardson
  • 5,567
  • 3
  • 17
  • 40
  • I haven't tried posting a response back, that could work. Thanks! – Harry Manback Apr 18 '17 at 03:03
  • You're very welcome! It's the only way to do it as far as I can see :) – Kyle Richardson Apr 18 '17 at 03:07
  • Not the most elegant solution, but it works. Thanks again. – Harry Manback Apr 18 '17 at 03:22
  • all of this doesn't explain how to return synchronously the callback from the receiver into the sending method – jck Mar 13 '18 at 13:52
  • 1
    No one asked how to do it synchronously. There is no synchronous communication between different windows. – Kyle Richardson Mar 13 '18 at 15:22
  • 5
    I realize this Q&A is long done, but sticking this here in case anyone else comes looking for a solution: _"Postmate is a promise-based API built on postMessage. It allows a parent page to speak with a child iFrame across origins with minimal effort."_ https://github.com/dollarshaveclub/postmate – James Fernandes Mar 21 '18 at 19:50
  • An alternative to Postmate is Comlink https://github.com/GoogleChromeLabs/comlink/ The description emphasizes web workers, but it works with iframes too. – DharmaTurtle Aug 25 '22 at 20:00