Javascript iframe 加载事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5975526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iframe onload event
提问by McRonald
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.
更新(); 当点击 iframe 内的链接并加载新页面时,不会调用。
What's the problem?
有什么问题?
回答by betamax
Short answer: You can't get the URL of pages on any domain other than yours. The URL you want can be gotten with:
简短回答:除了您的域之外,您无法获取任何域上页面的 URL。可以通过以下方式获取您想要的 URL:
document.getElementById("browse").contentWindow.location.href;
However, this URL will only be available when browsing sites on yourdomain due to the Same origin policy. It will be undefined and you will get a security error if you try on any other domain.
但是,由于同源策略,此 URL 仅在浏览您域中的站点时可用。它将是未定义的,如果您尝试任何其他域,您将收到安全错误。
So, if you want to get pages from other domains and you want to do this with pure javascript, you can't.
因此,如果您想从其他域获取页面,并且想使用纯 JavaScript 执行此操作,则不能。
Long answer: You coulduse a server-side proxy to load in the URLs requested in the iframe. Something like:
长答案:您可以使用服务器端代理加载 iframe 中请求的 URL。就像是:
http://yourdomain.com/proxy.php?url=http://www.google.com/
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.
然后在获取 URL 时获取 url 参数并将其放入“addr”输入中。
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.
这种做法真的不值得做;您将使用大量带宽,并且您将向想要通过防火墙代理并滥用您的代理以满足他们的需求的人开放您的站点。
回答by DanielB
You may add the handler directly after changing the src to let it work:
您可以在更改 src 后直接添加处理程序以使其工作:
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/