问题描述
我在应用程式中有这个Javascript程式码,可防止click::
< script language =javascripttype = 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>
基本上,它创建一个样式元素默认。然后,如果它不检测到点击劫持,它会删除它。所以,这样做,没有Javascript的每个人都可以看到的页面(尽管他们不会受到点击劫持)。
它适用于每一个浏览器(Internet Explorer除外),它会引发运行时错误异常。
您不能通过 innerHTML
设置< style>
元素的内容。我认为正确的属性名称是 cssText
但是我必须检查MSDN。
/ em>—
因此,您的代码可以执行此操作:
var styles = document.createElement('style');
style.type =text / css;
style.id =antiClickjack;
if('cssText'in style)
style.cssText =body {display:none!important;};
else
style.innerHTML =body {display:none!important;};
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 :-)
You can't set the content of a <style>
element via innerHTML
. I think the correct property name is cssText
but I'll have to check MSDN.
edit — yup that's it.
Thus your code can do this:
var style = document.createElement('style');
style.type = "text/css";
style.id = "antiClickjack";
if ('cssText' in style)
style.cssText = "body{display:none !important;}";
else
style.innerHTML = "body{display:none !important;}";
这篇关于Javascript以防止点击劫持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!