How to perform a function optionally if the page is loaded within an iframe?

Asked

Viewed 81 times

3

You can tell if a particular page is being opened inside a iframe?

I want that page to run a function when it is loaded through a iframe. Otherwise, I don’t want you to.

Is there any way to do that?

  • I think it’s possible with window.frameElement. I’m on the phone and can not test, but I think it is the solution. If I’m not mistaken, the value is null when the page is not loaded inside the iframe.

1 answer

0

The @Andersoncarloswoss suggestion may give security error. Have a comment (in English) here: https://html.spec.whatwg.org/multipage/browsers.html#dom-frameelement

One solution I found, was in this post of the OS in English: https://stackoverflow.com/a/7769187/4730201

The code is this:

var ehFrame = window.frames.length + ':' + parent.frames.length;

Basically returns:

'0:0' when there are no frames
'1:1' when executed in the "parent" window that has the iframe
'0:1' when executed in the "daughter window"

I think this should help you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.