最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - change iframe content jquery - Stack Overflow

programmeradmin4浏览0评论

I'd like to change my iframe content but I don't understand how

<html>
    <head>
        <title>test</title>
        <script src=".11.0/jquery.min.js"></script>
    </head>
    <body>
        <iframe id="frame" width="100%" height="95%" src=""></iframe>
    <script type=text/javascript >
        $('#frame').contents().find( "body" ).html('<p>hi</p>')
    </script>
    </body>

</html>

With this code I always have my google page and not a ifram with hi

I'd like to change my iframe content but I don't understand how

<html>
    <head>
        <title>test</title>
        <script src="http://ajax.googleapis./ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    </head>
    <body>
        <iframe id="frame" width="100%" height="95%" src="http://google."></iframe>
    <script type=text/javascript >
        $('#frame').contents().find( "body" ).html('<p>hi</p>')
    </script>
    </body>

</html>

With this code I always have my google page and not a ifram with hi

Share Improve this question asked Apr 7, 2014 at 13:15 AjouveAjouve 10.1k27 gold badges94 silver badges153 bronze badges 2
  • 1 You can't, you don't have access to cross origin domains in an iframe due to the same-origin policy, and if that weren't enough Google uses x-frame-options and can't be framed. – adeneo Commented Apr 7, 2014 at 13:17
  • there is an exemple with jquery api.jquery./contents but it doesn't works for me, a ok I understand because the request is from jquery, is there a solution to change ifram content ? – Ajouve Commented Apr 7, 2014 at 13:20
Add a ment  | 

3 Answers 3

Reset to default 6
<script type="text/javascript">
  $(document).ready(function(){        
       $('#frame').on('load', function() {
           $(this).contents().find( "body" ).html('<p>hi</p>');
       });
  });
</script>

While this is right, the content will never change as you are trying to modify the body of an external resource. You cannot do this due to cross-site scripting rules.

EDIT:

The only way to do it is to do what @user1153551 did and replace the whole document.

Check this Demo jsFiddle

you have to use load event within the iframe's document and calling out to a load function in the containing document to replace to a body contain.

jQuery

$('#frame').load(function() {
  $('#frame').replaceWith('<p>hi</p>');
});

HTML

<iframe id="frame" width="100%" height="95%" src="http://w3schools."></iframe>

Use .replaceWith() jQuery Method.

use document.ready

<script type=text/javascript >
  $(document).ready(function(){        
      $('#frame').on('load', function() {
       $(this).contents().find( "body" ).html('<p>hi</p>');
     });
  });
</script>
发布评论

评论列表(0)

  1. 暂无评论