Here is the problem: you can do it of course, but asynchronously. That said, when you start loading the iframe source page by Ajax, it won't block execution of the script, so further execution might override the result of your callback.
I prefer doing it with jQuery. Consider this:
<html>
<head>
<title></title>
<script type="text/javascript" src="scripts/jquery-1.7.1.min.js"></script>
</head>
<body>
<iframe id="myIframe" src="test.html"></iframe>
<script type="text/javascript">
$(document).ready(function() {
var content;
var iFrameSource = $("#myIframe").attr('src') //will assign "test.html"
$.get(iFrameSource, function(data) {
content = data; //will not be assigned immediately after the call to get
alert('Load was performed: ' + data);
document.write(content);
});
}); </script>
// at this moment, content is still not assigned
</body>
</html>
If you try to use variable
content
, it will be still undefined. So, instead of attempting to write a function which would return the content, try to do all you need in the callback. Better yet, try to use the function
load
to load your content onto some HTML element:
<html>
<head>
<title></title>
<script type="text/javascript" src="scripts/jquery-1.7.1.min.js"></script>
</head>
<body>
<iframe id="myIframe" src="test.html"></iframe>
<h2 id="sink">Initial value</h2>
<script type="text/javascript">
$(document).ready(function() {
var content;
var iFrameSource = $("#myIframe").attr('src')
$("#sink").load(iFrameSource)
}); </script>
</body>
</html>
If you need to do some calculation on the loaded content, do it in a callback when a resource is loaded. Don't forget asynchronous nature of Ajax.
—SA