0

i am trying to edit content from iframe using jquery but nothing really seems to happen. Can anyone explain why please?

 <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<iframe src="//api.jquery.com/" width="80%" height="600" id="frameDemo"></iframe>

    <script>
    $( "#frameDemo" ).contents().find( ".page-title" ).text('My html');
    </script>
Arkan Kalu
  • 403
  • 2
  • 4
  • 16
  • You can't because of security. What if I could load a page and run some javascript on it. Would be messed up right? – Michelangelo Dec 20 '15 at 15:48
  • Is it possible then to iframe some website to my website and edit certain parts? – Arkan Kalu Dec 20 '15 at 15:49
  • Pleas see this answer. You can't http://stackoverflow.com/a/26329643/4194436 – Michelangelo Dec 20 '15 at 15:51
  • Possible duplicate of [Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement'](http://stackoverflow.com/questions/26329519/uncaught-securityerror-failed-to-read-the-contentdocument-property-from-html) – Michelangelo Dec 20 '15 at 15:51
  • What about this post saying that contents() can manipulate parts of an iframe? http://stackoverflow.com/questions/5924936/change-html-of-an-iframe-with-jquery – Arkan Kalu Dec 20 '15 at 15:53
  • That is from 4 years ago, if you looked at your console you will see the error and it also tells you why you can't access it. – Michelangelo Dec 20 '15 at 15:56

1 Answers1

1

You cannot access or manipulate content from another domain in this way. This is blocked by something called the same-origin policy.

As the MDN page on this subject states, the same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin. It is a critical security mechanism for isolating potentially malicious scripts.

It is however possible to manipulate the HTML of an iframe that is on the same domain. You'd do that like this:

$("#frameid").contents().find("div").html('My html');

See here: Change HTML of an iFrame with jQuery?

Community
  • 1
  • 1
James Hibbard
  • 16,490
  • 14
  • 62
  • 74