Javascript to prevent clickjacking

谁说我不能喝 提交于 2019-12-13 12:51:18

问题


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 :-)


回答1:


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;}";



回答2:


In the document HEAD element, add the following:

<style id="antiClickjack">body{display:none !important;}</style>

<script type="text/javascript">
   if (self === top) {
       var antiClickjack = document.getElementById("antiClickjack");
       antiClickjack.parentNode.removeChild(antiClickjack);
   } else {
       top.location = self.location;
   }
</script>


来源:https://stackoverflow.com/questions/8169297/javascript-to-prevent-clickjacking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!