Alen
Alen

Reputation: 31

Get frame contents with jQuery

main.html has this code:

<iframe id="myframe" src="myframe.html"></iframe>

and I trigger this code inside main.html:

alert($('#myframe').contents().find('#mypage').contents().find('html').html());

myframe.html has this code:

<frameset>
<frame id="mypage" src="mypage.html">
</frameset>

mypage.html has all this code:

<!DOCTYPE HTML>
<html>
<head>
</head>
hello world!
</html>

I want to get all the HTML code of the mypage.html from within the main.html page, but I fail. What is the problem with the way I do it?

Upvotes: 1

Views: 3261

Answers (3)

Stefan Steiger
Stefan Steiger

Reputation: 82196

I was facing the same problem.

I was able to resolve it.

In my example:

myframe = ReportFrameReportViewerControl
mypage = report

This is the code to get the html (note that all sites need to be on the same domain):

function bla()
{
    var str = 
    $(
            $(
                $("#ReportFrameReportViewerControl")[0].contentWindow.document
            )
            .find("#report")[0].contentWindow.document
        ).find("html").html()
        ;

        alert(str);
}

You might want to place it onto a button that you can press once the page loaded:

<input type="button" value="test" onclick="bla();" />

Also, if you want to get the html automagically once the page is loaded, you need to register the onload function of both myframe & mypage.

Like this (replace setTableSize with bla):

$(document).ready(function () 
{
    $('#ReportFrameReportViewerControl').load(function () 
    {
        //setNewHeight();
        //alert("Loading");

        setTableSize();

        $(
            $("#ReportFrameReportViewerControl")[0].contentWindow.document
        )
        .find("#report").load(function () 
        {
            //alert("load report");
            setTableSize();
        }
        ); // End load #report


    }); // End Function load #ReportFrameReportViewerControl


}); // End Function document.ready

Upvotes: 1

Michael
Michael

Reputation: 133

First of all you need to include the jquery library at main.html. Secondly, Chrome returns the next error:

Unsafe JavaScript attempt to access frame with URL file:///../myframe.html from frame with URL file:///../main.html. Domains, protocols and ports must match.

So it's a security problem

Upvotes: 0

anthony sottile
anthony sottile

Reputation: 69964

Technically I don't think you can do it with the frames as that would be a security problem.

You could load the source of the inner frame with ajax if you really needed to get at it. But it certainly wouldn't be live

Upvotes: 0

Related Questions