Iframe onload event

I have a simple piece of code:

<script> function change(){document.getElementById("browse").src = document.getElementById("addr").value;} function update(){document.getElementById("addr").value = document.getElementById("browse").src;} <script> <input type="text" id="addr"><input type="button" value="Go" onclick="change();"> <iframe id="browse" style="width:100%;height:100%" onload="update();"></iframe> 

update (); It is not called when, for example, the link to the iframe link was clicked and a new page was loaded.

What is the problem?

+3
javascript html
May 12 '11 at 8:46
source share
2 answers

Short answer: you cannot get the URL of pages in any domain other than yours. The URL you want can be obtained using:

 document.getElementById("browse").contentWindow.location.href; 

However, this URL will only be available when browsing sites in your domain due to the same origin rule . This will be undefined and you will receive a security error message if you try any other domain.

So, if you want to receive pages from other domains, and you want to do this with pure javascript, you cannot.

Long answer: you can use a server side proxy to load in the URLs requested in the iframe. Something like:

http://yourdomain.com/proxy.php?url=http://www.google.com/

And then when the url gets the url parameter and puts it in the addr input.

This approach is really not worth doing; You will use a lot of bandwidth, and you will open your site for people who want a proxy server through a firewall, and abuse your proxy server with your needs.

+7
May 12 '11 at 9:51
source share

You can add a handler immediately after changing src so that it works:

 function change(){ document.getElementById("browse").src = document.getElementById("addr").value; document.getElementById("browse").onload = function (e){alert(e);} } 

Take a look at this example http://jsfiddle.net/xkBF3/

+6
May 12 '11 at 8:50
source share



All Articles