Home » Javascript » how to correctly postMessage into an iframe that has sandbox attribute enabled

how to correctly postMessage into an iframe that has sandbox attribute enabled

Posted by: admin June 30, 2018 Leave a comment

Questions:

See below sample code

  • If I comment out the “sandbox” attribute line, everything run just fine.
  • if I uncomment the “sandbox” attribute line, in chrome open developer console, we will see error “Failed to execute ‘postMessage’ on ‘DOMWindow’: The target origin provided (‘https://www.bing.com‘) does not match the recipient window’s origin (‘null’).”

any idea how to solve this problem?

const iframeElement = document.createElement("iframe");
iframeElement.src = "https://www.bing.com"
//iframeElement.setAttribute("sandbox", "allow-forms allow-modals allow-popups allow-scripts");
iframeElement.onload = (e) => {
  iframeElement.contentWindow.postMessage("foo", "https://www.bing.com");
};

const containerElement = document.getElementById("place-holder-for-iframe");
containerElement.appendChild(iframeElement);

You can try it out with this jsbin link
http://jsbin.com/gafobulife/edit?js,output

  • open js bin link in chrome
  • open chrome developer tool –> go to Console tab
  • uncomment the sandbox line
  • click “run with js” from jsbin
Answers: