iframe postMessage with Promise
Posted at 2020-05-18

iframe postMessage with Promise


sender.js

document.domain = 'example.com'
let postMsg
  // reference to iframe element
  postMsg = window.document.getElementById('headerFrameEl').contentWindow.postMessage
  let __seq = 0; // global sequence
  
  function postMessagePromise(msg){
    return new Promise(function(resolve, reject) {
      let seq = ++__seq;

      let event_ref = window.addEventListener("message", function(resp){
        if (resp && resp.data && resp.data.__seq && resp.data.__seq == seq){
          window.removeEventListener("message", event_ref)
          resolve(resp.data)
        }
      }, false);

      postMsg({...msg, __seq:seq}, '*')
    });
  }
  
  // test
  postMessagePromise({msg:'getSomething'})
  .then((r)=>{ console.log('response from iframe', r) })
 

frame.js

  document.domain = 'example.com'  
  window.addEventListener("message", receiveMessage, false);
  function receiveMessage(e){
    if (e && e.data && e.data.__seq){
      e.source.postMessage({any:'value', __seq:e.data.__seq}, '*');
    }
  };


Protocol, hostname and port must be the same of your domain, if you want to access a frame.

Comments 0

Post a Comment