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
3 Answers
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>