Javascript 防止点击劫持
我的应用程序中有这个 Javascript 片段来防止点击劫持:
<script language="javascript" type="text/javascript">
var style = document.createElement('style');
style.type = "text/css";
style.id = "antiClickjack";
style.innerHTML = "body{display:none !important;}";
document.head.appendChild(style);
if (self === top) {
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
} else {
top.location = self.location;
}
</script>
基本上,它会创建一个样式元素(动态 CSS)来默认隐藏当前页面的正文。然后,如果没有检测到点击劫持,则会将其删除。因此,通过这种方式,每个没有 JavaScript 的人也可以看到该页面(尽管他们不会受到点击劫持的保护)。
它适用于除 Internet Explorer 之外的所有浏览器,Internet Explorer 会引发未知运行时错误异常。有人对如何解决这个问题有建议吗?
谢谢 :-)
I have this Javascript snippet in my application to prevent clickjacking:
<script language="javascript" type="text/javascript">
var style = document.createElement('style');
style.type = "text/css";
style.id = "antiClickjack";
style.innerHTML = "body{display:none !important;}";
document.head.appendChild(style);
if (self === top) {
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
} else {
top.location = self.location;
}
</script>
Basically, it creates a style element (CSS on the fly) to hide the body of the current page by default. Then, if it doesn't detect clickjacking, it deletes it. So, doing it this way, everyone who doesn't have Javascript can see the page too (although they won't be protected from clickjacking).
It works for every browser except for Internet Explorer, which throws a Unknown runtime error exception. Does someone have a suggestion on how to fix this?
Thanks :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法通过
innerHTML
设置元素的内容。我认为正确的属性名称是
cssText
但我必须检查 MSDN。编辑 - 是的,就是这样。
因此您的代码可以执行以下操作:
You can't set the content of a
<style>
element viainnerHTML
. I think the correct property name iscssText
but I'll have to check MSDN.edit — yup that's it.
Thus your code can do this:
在文档 HEAD 元素中,添加以下内容:
In the document HEAD element, add the following: