如果未正确加载,则隐藏 iframe

Hide iframes if not correctly loaded

我的页面上有几个指向外部网站的 iframe。如果这些服务中断或更改,我想隐藏这些 iframe 而不是在我的页面上显示错误消息。 有什么方法可以在 Javascript 中找出 iframe 是否已正确加载? 我添加了一个 class 来隐藏 iframe,然后在 iframe 准备就绪时使用 jQuery 将其删除,如下所示:

$('#widget').ready(function () {
    $('#widget').removeClass('hidden');
});

当我在 iframe src 中放入无效的 URL 时,它仍然会删除隐藏的 class,显示错误的 iframe。 我的问题有两个:

谢谢!

你可能无法使用 Javascript 做你想做的事,你需要服务器端的东西,例如 PHP。



但是,这里有一些有用的地方可以查找更多信息:


您可以在使用此 JQuery 函数加载 iframe 后 运行 编码:

$('#myIframe').load(function(){
    //your code (will be called once iframe is done loading)
});

查看 this Stack Overflow question and answers 关于 iframe 加载。


要定位函数内的特定元素,请执行:

$('iframe').aFunction(function() { this.doSomething(); } );

查看 this Stack Overflow question 和有关 "this" 的答案。

您的问题可以归结为:

how can I check if an URL exists and the website is alive from Javascript ?

答案分为:

  • 对于 内部 URLs,使用 AJAX 并检查响应代码:如果它是 2xx3xx(例如200或302),没关系。如果它是 4xx5xx(例如 404 或 500),那就不好了。在 a similar answer.

  • 上阅读更多内容
  • 对于 外部 URLs,由于称为 same-origin policy.[=18 的安全措施,您不能这样做=]

由于您似乎指向外部 URLs,因此我的建议是:

创建一个服务器端组件(一个 Servlet、一个 RESTful WebService、一个 Struts2 操作等...根据您使用的服务器端技术,您喜欢什么)为您执行检查,并 return 包含数据(如果有)的流式响应和您可以检查错误的 HTTP 响应代码。然后从 <iframe>s 调用你的组件 URL.