Detect if a page is within a iframe - serverside

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.


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.


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