1

I have the following JavaScript code:

myFrame.src = pathToCourseContents + "/otherComponents/myData.htm";

After this line is executed:

myFrame.src equals "http://myServer.com/otherComponents/myData.htm"

If I put this URL address into FireFox I do get a web page with information coming up.

What I'm trying to get is the contents of myData.htm in the form of a string.

I thought this would work:

var myString = myFrame.contentWindow.document.body.outerHTML

but myFrame.contentWindow appears to be blank.

What am I doing wrong?

Is there JavaScript code that will work to get the html content in the form of a string?

user737058
  • 69
  • 1
  • 5
  • 1
    Presumably they are on the same domain? - contentWindow should be contentDocument for anything above IE8 (http://stackoverflow.com/a/6582370/246342) Are you waiting to the budy to load fully? – Alex K. Apr 23 '13 at 17:35
  • I am stepping through the code in FireBug. If I put a break on the line: myFrame.contentWindow.document.body.outerHTML , and then step over it...shouldn't that give time enough for the body to fully load? How do I slow it down? – user737058 Apr 23 '13 at 17:57
  • Are you looking for `myFrame.addEventListener("load", function() { ... })`? – apsillers Apr 23 '13 at 18:10
  • I'm not sure what you mean by "looking for"? Can you elaborate? Thanks. – user737058 Apr 23 '13 at 18:54

3 Answers3

1

You can try using this:

document.getElementsByTagName("html")[0]
Floremin
  • 3,969
  • 15
  • 20
0

contentWindow is most often blank when you load url from diferent domain. It is prohibitied to access such content, because of security. If this is your case, you're doomed (well, there are workarounds, like proxy through the server that serves the container page, so that browser thinks they are from the same domain; or set document.domain in both files, if you control both of them; etc.).

0

If you're not encountering the same origin policy, it may be that you're trying to access nodes before they exist (i.e. before the DOM is ready).

A simple solution is to add an event listener on the <iframe> for the load event.

myFrame.addEventListener('load', function () { // add a listener
    console.log( // do what you want
        '<iframe> loaded\n',
        myFrame.contentWindow,   // the <iframe>'s Window
        myFrame.contentDocument, // the <iframe>'s document
        '\n',
        myFrame.contentDocument.body.outerHTML
    );
});
// set src after so that listener exists before event raised
myFrame.src = 'http://fiddle.jshell.net/'; // same origin pass

example fiddle

.contentWindow get's cleared every time you refresh so you can't add page load listeners to it that will give you the result you want, but you can listen for other events from within the <iframe> there.

Paul S.
  • 64,864
  • 9
  • 122
  • 138