【问题标题】:Determine if a site will open in an iframe确定网站是否会在 iframe 中打开
【发布时间】:2013-09-20 16:11:41
【问题描述】:

如果页面上的图片加载失败,我们有 onerror 函数可以加载默认图片。

是否有将网站加载到 iFrame 的等价物?

例如mashable.com 可以加载到 iFrame 中,而许多社交网站,例如Facebook、Twitter 等不能。

因此,当用户尝试加载时,例如Twitter 并没有显示任何内容,我想要一条消息显示“此页面无法显示”,然后在新选项卡中打开链接并在 3 秒后引导它们。

不确定这是否可能。

【问题讨论】:

  • @MilchePatern — 问题是询问阻止在 iframe 中加载的网站,而不是完全错误的 URL。
  • 嗯,谢谢.. 我需要一杯咖啡。相关:stackoverflow.com/questions/4548984/…
  • 查看此答案:stackoverflow.com/questions/4548984/detect-if-the-if​​rame-content-has-loaded-successfully#answer-4637351

标签: html iframe


【解决方案1】:

由于安全限制,这在客户端是不可能的。但是,您有两种替代解决方案:

  • 从服务器调用并检查 X-Frame-Options 标头。
  • 或者,您可以设置一个超时,并假设如果一段时间后未触发加载事件,则无法加载页面。

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

【讨论】:

【解决方案2】:

我遇到了同样的问题,我使用的是 AngularJS,我使用下面的方法让它工作。希望对你有帮助。。

  1. 在 html 中设置 iframe

    <div ng-if="!iframeError">
      <iframe id="iframeID" src="http://www.google.com" height="500px"></iframe>
    </div>
    <div ng-if="iframeError">Not Supported</div>
    
  2. 如果 iframe 可用,我会设置监听间隔

    var ife = setInterval(function () {
    if ($("#iframeID")) {
     $("#iframeID").load(function (ev) {
      var iframe = $("#iframeID");
      var iframeDocument;
      try {
      iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
      }
      catch (e) {
       window.open("http://www.google.com");
       $scope.iframeError = true;
       //I opened the url in new page
       //you can handle it any way you want
      }
     });
     clearInterval(ife);
     }
    }, 200);
    

【讨论】:

    【解决方案3】:

    if(frames){if(top.frames.length&gt;0){ YOUR CODE HERE }}

    如果你想删除父级:

    if(frames){if(top.frames.length&gt;0){top.location.href=self.location;}}

    【讨论】:

      【解决方案4】:

      您可以将代码包装起来:

      if($("#iframe1").find('iframe').length > 0) {
          //Site allowed
      }
      else {
          //Site blocked.
      }
      

      【讨论】:

        【解决方案5】:
        var isInIframe = (window.location != window.parent.location);
        
        if (isInIframe) {
            alert("Window is in iframe");
            // Do what you want
            //top.location.href=self.location;
        } else {
            alert("Window is not in iframe");
        }
        

        【讨论】:

        • 请说明您的代码的作用以及它如何回答问题。如果您得到一个代码 sn-p 作为答案,您可能不知道如何处理它。答案应该为 OP 和未来的访问者提供有关如何调试和解决问题的指导。指出您的代码背后的想法是什么,对理解问题以及应用或修改您的解决方案有很大帮助。
        • 请看我放在这里的截图callpanipat.com/blog-discussion.php
        • 查看差异时,尝试使用模式更改按钮(内联、并排、并排降价)。因此,您可以选择最能看到变化的位置。
        猜你喜欢
        • 2018-02-12
        • 1970-01-01
        • 1970-01-01
        • 2014-06-12
        • 2018-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        相关资源
        最近更新 更多