Detect if a page is within a iframe – serverside

How can I detect server-side (c#, asp.net mvc) if the loaded page is within a iframe? Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This is not possible, however.

<iframe src="mypage?iframe=yes"></iframe>

and then check serverside if the querystring contains iframe=yes
or with the Referer header send by the browser.

Method 2

Use the following Code inside the form:

<asp:HiddenField ID="hfIsInIframe" runat="server" />
<script type="text/javascript">
    var isInIFrame = (self != top);
    $('#<%= hfIsInIframe.ClientID %>').val(isInIFrame);
</script>

Then you can check easily if it’s an iFrame in the code-behind:

bool bIsInIFrame = (hfIsInIframe.Value == "true");

Tested and worked for me.

Edit: Please note that you require jQuery to run my code above. To run it without jQuery just use some code like the following (untested) code to set the value of the hidden field:

document.getElementById('<%= hfIsInIframe.ClientID %>').value = isInIFrame;

Edit 2: This only works when the page was loaded once. If someone have idea’s to improve this, let me know. In my case I luckily only need the value after an postback.

Method 3

There is no way of checking this that will fit your requirement of “secure” as stated in your comment on @WTP’s answer.

Method 4

I don’t think the server-side can do this, so why not put a hidden control in your page that will be in the iframe? When the URL in the iframe loads, you can add some client-side code to set the hidden input to indicate you are in an iframe. The easiest check would be on the client-side in an onload method, like this:

// Set hidden input
someHiddenInput.value = self != top

It’s more secure than the querystring, but it still might not be enough security for you.

My 2 cents.

Method 5

Old question but why not a more simplistic approach like

var isFramed = self !== parent


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x