Javascript iframe加载完成后如何调用javascript函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14667770/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:33:14  来源:igfitidea点击:

How to call a javascript function when iframe finished loading?

javascripthtmliframe

提问by user1788736

Could any one tell me how I can detect if an iframe has finished loading so I can call a javascript function and alert the user that iframe finished loading and do some other process inside the javascript function? (Note my iframe is my own site) Can I fire callback from within the iframe as I can have control over it? if yes how ?

谁能告诉我如何检测 iframe 是否已完成加载,以便我可以调用 javascript 函数并提醒用户 iframe 已完成加载并在 javascript 函数中执行其他一些过程?(注意我的 iframe 是我自己的网站)我可以从 iframe 内部触发回调,因为我可以控制它吗?如果是怎么办?

<iframe id ='myframe' src='http://www.example.com/doit.php'></iframe>

回答by pbaris

try this

尝试这个

<iframe id ='myframe' src='http://www.mysite.com/doit.php' onload="onLoadHandler();"></iframe>

<script type="text/javascript">
function onLoadHandler() {
    alert('loaded');
}
</script>

回答by John Conde

Handle it just like anything loading:

像加载任何东西一样处理它:

$('#myframe').on('load', function() {
    // Handler for "load" called.
});

Obsolete answer:

过时的答案:

$('#myframe').load(function() {
  // Handler for .load() called.
});

回答by forastero

With just plain javascript

只使用普通的 javascript

document.querySelector('#myframe').addEventListener("load", ev => {
    // your stuff
})