StudioTime
StudioTime

Reputation: 24019

Determine if a site will open in an iframe

If an image fails to load on a page we have the onerror function which can load a default image.

Is there an equivalent for loading a site into an iFrame?

E.g. mashable.com can be loaded into an iFrame whereas many social sites e.g. Facebook, Twitter et al can not.

So when a user tries to load e.g. Twitter and nothing is shown, I'd like a message to show saying "this page cannot be displayed" and then open the link in a new tab instead and direct them after say 3 seconds.

Not sure if this is possible.

Upvotes: 10

Views: 7718

Answers (5)

Satpal Tanan
Satpal Tanan

Reputation: 1108

I had the same problem and I was using AngularJS, I got it working using the method below. Hope it helps..

  1. Set an iframe in the html

    <div ng-if="!iframeError">
      <iframe id="iframeID" src="http://www.google.com" height="500px"></iframe>
    </div>
    <div ng-if="iframeError">Not Supported</div>
    
  2. I set an interval for listening if the iframe is available

    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);
    

Upvotes: 2

vinod
vinod

Reputation: 2880

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");
}

Upvotes: 0

hectorct
hectorct

Reputation: 3555

Due to security restrictions, that isn't possible from the client side. However you have two alternative solutions:

  • Do a call from the server and check for X-Frame-Options headers.
  • Alternatively you can set a timeout and assume the page can't be loaded if the load event isn't fired after some time.

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

Upvotes: 4

user3534071
user3534071

Reputation: 1

You can wrap the code around:

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

Upvotes: 0

aryan kumar
aryan kumar

Reputation: 151

if(frames){if(top.frames.length>0){ YOUR CODE HERE }}

if you want to remove parent the:

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

Upvotes: 0

Related Questions