I've 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(); is not called when e.g. link inside the iframe was clicked and new page loaded.
What's the problem?
I've 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(); is not called when e.g. link inside the iframe was clicked and new page loaded.
What's the problem?
Share Improve this question edited May 12, 2011 at 8:57 McRonald asked May 12, 2011 at 8:46 McRonaldMcRonald 1,0054 gold badges11 silver badges13 bronze badges 1- 1 When you say update() is not called, it is actually not called or does your script just encounter an error and die? (You can check with Chrome Dev Tools or Firebug.) – lpd Commented May 12, 2011 at 8:50
2 Answers
Reset to default 7Short answer: You can't get the URL of pages on any domain other than yours. The URL you want can be gotten with:
document.getElementById("browse").contentWindow.location.href;
However, this URL will only be available when browsing sites on your domain due to the Same origin policy. It will be undefined and you will get a security error if you try on any other domain.
So, if you want to get pages from other domains and you want to do this with pure javascript, you can't.
Long answer: You could 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 getting the URL get the url parameter and put that in the 'addr' input.
This approach is really not worth doing; You will use a lot of bandwidth and you will open your site up to people wanting to proxy through a firewall and abusing your proxy for their needs.
You may add the handler directly after changing the src to let it work:
function change(){
document.getElementById("browse").src = document.getElementById("addr").value;
document.getElementById("browse").onload = function (e){alert(e);}
}
Have a look at this example http://jsfiddle.net/xkBF3/