Reputation: 10234
I'm trying to create a simple test to modify the content of an iframe from its parent container and to modify the content of the parent container from the iframe. Here's what I have so far:
first.html:
<!doctype html>
<html>
<head>
<title>First</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="shared.js"></script>
<script type="text/javascript" src="first.js"></script>
</head>
<body>
<h1>First</h1>
<iframe src="http://localhost:3000/second.html"></iframe>
</body>
</html>
second.html:
<!doctype html>
<html>
<head>
<title>Second</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="shared.js"></script>
<script type="text/javascript" src="second.js"></script>
</head>
<body>
<h1>Second</h1>
</body>
</html>
shared.js:
function modifyContent(targetContainerElement, targetSelector, sourceString) {
$(targetContainerElement).find(targetSelector).html("Modified by " + sourceString + "!");
}
first.js:
$(document).ready(function() {
var iframe = $("iframe");
modifyContent(iframe.contents(), "h1", "First");
});
second.js:
$(document).ready(function() {
if (!top.document)
return;
modifyContent(top.document.body, "h1", "Second");
});
To run the code, I use python -m SimpleHTTPServer 3000
and navigate to localhost:3000/first.html
. The first header is modified and says "Modified by Second!" but the second header just says "Second". What am I missing here?
Upvotes: 2
Views: 5784
Reputation:
Try changing the h1 tag inside the iframe when it's completely loaded:
$(document).ready(function() {
var iframe = $("iframe");
iframe.load(function ()
{
modifyContent(iframe.contents(), "h1", "First");
});
});
Plus I think you should rewrite modifyContent
:
function modifyContent(isJquery, targetContainerElement, targetSelector, sourceString)
{
if ( isJquery )
targetContainerElement.find(targetSelector).html("Modified by " + sourceString + "!");
else
$(targetContainerElement).find(targetSelector).html("Modified by " + sourceString + "!");
}
just targetContainerElement
would work cause you don't really need to wrap it in $() since it's already a jquery object
Upvotes: 2