0

I have this jsfiddle where i load inside an iframe an http url. After i want to delete the content and replace it with html code i create with javascript. This alternate will happen many times. When i try with the following code i get this error Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "https://fiddle.jshell.net" from accessing a frame with origin "https://jsfiddle.net". Protocols, domains, and ports must match.

HTML

<iframe id = "Preview" src ="https://jsfiddle.net/"></iframe>
<button onclick = "changeSRCtoLocal()">Click me</button>
<br>
<span>click at the button to change html content of iframe</span>

JS

function changeSRCtoLocal(){
  document.getElementById('Preview').src = "about:blank";
  var iframe = document.getElementById('Preview'),
  iframedoc = iframe.contentDocument || iframe.contentWindow.document;

  iframedoc.body.innerHTML = "<html>How can someone view me?</html>";
  alert()
}

UPDATE

To any answers that say that you can't do it please explain why this exaple works??

prieston
  • 1,426
  • 2
  • 18
  • 39
  • [Ways to circumvent the same-origin policy](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy) – adeneo Feb 25 '16 at 12:11
  • So should i set the `document.domain` of the iframe? Can you post an answer to my question of how to achieve it? – prieston Feb 25 '16 at 12:17
  • You can't, unless you control the page you're loading in the iFrame and can add certain headers etc. – adeneo Feb 25 '16 at 12:23
  • Check [this example](https://jsfiddle.net/dvpx63nk/22/) which does what i want but with another way!! You can do it but my way is not working and i dont know why. – prieston Feb 25 '16 at 12:49
  • You can change the source of the iFrame, you can change the entire content of the iFrame, but you can not access the contents of an iframe that is loaded from a different domain, if the same-origin policy applies – adeneo Feb 25 '16 at 21:57
  • thats what i am asking.. How can I change the entire content of the iFrame without changing the src? – prieston Feb 26 '16 at 08:21

0 Answers0