C# 检测页面是否在 iframe 内 - 服务器端

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1179333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:09:39  来源:igfitidea点击:

Detect if a page is within a iframe - serverside

c#asp.nethtmlasp.net-mvc

提问by pistacchio

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

如果加载的页面在 iframe 内,如何检测服务器端(c#、asp.net mvc)?谢谢

采纳答案by pistacchio

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.

然后检查服务器端查询字符串是否包含 iframe=yes 或浏览器发送的 Referer 标头。

回答by ceejayoz

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

正如您对@WTP 回答的评论中所述,没有办法检查这一点是否符合您对“安全”的要求。

回答by nickytonline

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:

我不认为服务器端可以做到这一点,那么为什么不在您的页面中放置一个隐藏的控件,它将位于 iframe 中呢?当 iframe 中的 URL 加载时,您可以添加一些客户端代码来设置隐藏输入以指示您在 iframe 中。最简单的检查是在客户端的 onload 方法中,如下所示:

// 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.

我的 2 美分。

回答by Vortex852456

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:

然后您可以轻松检查它是否是代码隐藏中的 iFrame:

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:

编辑:请注意,您需要 jQuery 才能运行我上面的代码。要在没有 jQuery 的情况下运行它,只需使用如下(未经测试的)代码来设置隐藏字段的值:

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.

编辑 2:这仅在页面加载一次时有效。如果有人有改进这一点的想法,请告诉我。就我而言,幸运的是我只需要回发后的值。

回答by Eric Herlitz

Old question but why not a more simplistic approach like

老问题,但为什么不采用更简单的方法,例如

var isFramed = self !== parent