Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

javascript - iframe onload event

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Short 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...