Sakthivel
Sakthivel

Reputation: 1941

Fetching page source

I have the following code in my page

<html>
<head> 
    <title>testpage</title>
    <script language = 'javascript'>function fchange(){alert(document.getElementById("ifrm").value);</script>
</head>
<body>
    <iframe id = 'ifrm' src = 'http://www.google.com' width = '700' height='500'></iframe><input type='button' onclick = 'fchange()' value = 'clickhere'>
</body>
</html>

From this I click the button and an alert box dispalys undefined. But I need the content or the source of the page ('http://www.google.com'). Please help me to do this.

Thanks in advance...

Upvotes: 0

Views: 226

Answers (3)

Joel
Joel

Reputation: 19358

If you want the source of the iframe, you would need to access the document object of the iframe.

function fchange() 
{
    alert(document.getElementById("ifrm").contentWindow.document.body.innerHTML);
}

As mentioned by others, you cannot get the source of an iframe which points to a page outside your domain.

Upvotes: 2

Greg
Greg

Reputation: 321588

You can't do this, as it breaks the same-origin policy.

If both pages are on the same domain then you can with do what @Joel suggests, or the slightly more old fashioned:

window.frames['ifrm'].document.body.innerHTML;

You'll need <iframe name="ifrm" ...> for this to work.

Upvotes: 2

Jamol
Jamol

Reputation: 2291

You need to have back-end script for that. I think that's the only way. AJAX would not allow to make a request to other domains for security reasons.

Upvotes: 1

Related Questions