Arkan Kalu
Arkan Kalu

Reputation: 403

Edit iframe content with jquery

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>

Upvotes: 0

Views: 121

Answers (1)

James Hibbard
James Hibbard

Reputation: 17755

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?

Upvotes: 1

Related Questions