使脚本等到iframe加载后再运行

使脚本等到iframe加载后再运行

问题描述:

我正在处理的网站在iframe上有一个Live Chat插件。如果没有可用的代理,我正在尝试更改图像。我的代码在控制台上工作,但网站上没有任何内容。

The site I'm working on has a Live Chat plugin on an iframe. I'm trying to change an image if there are no agents available. My code works on the console, but nothing on the site.

var LiveChatStatus = $("iframe").contents().find(".agentStatus").html();
if (LiveChatStatus =="Offline"){
    $('#liveChat').html('<img src="%%GLOBAL_ShopPath%%/product_images/theme_images/liveoffline.png">');
}

我试过这个:

$('iframe').ready(function(){
    var LiveChatStatus = $("iframe").contents().find(".agentStatus").html();
    if (LiveChatStatus =="Offline"){
        $('#liveChat').html('<img src="%%GLOBAL_ShopPath%%/product_images/theme_images/liveoffline.png">');
    }
});

这个:

$(document).ready(function(){
   var LiveChatStatus = $("iframe").contents().find(".agentStatus").html();
   if (LiveChatStatus =="Offline"){
       $('#liveChat').html('<img src="%%GLOBAL_ShopPath%%/product_images/theme_images/liveoffline.png">');
   }
});

但两种方式都不起作用

最好的解决方案是在父级中定义一个函数,例如函数iframeLoaded(){...} 然后在iframe中使用:

The best solution is to define a function in your parent such as function iframeLoaded(){...} and then in the iframe use:

$(function(){
    parent.iframeLoaded();
})

这适用于跨浏览器。

如果您无法更改iframe中的代码,您最好的解决方案是将加载事件附加到iframe ..

If you cannot change the code within the iframe, your best solution will be to attach the load event to the iframe..

$(function(){
    $('iframe').on('load', function(){some code here...}); //attach the load event listener before adding the src of the iframe to prevent from the handler to miss the event..
    $('iframe').attr('src','http://www.iframe-source.com/'); //add iframe src
});