How to prevent my site page from being loaded into other website iframe?

后端 未结 3 1673
甜味超标
甜味超标 2021-02-06 14:44

We have many gaming websites, among them I am hosting exclusive games on my server, and i don\'t want to access my games to other websites from my server. I want to restrict the

3条回答
  •  生来不讨喜
    2021-02-06 15:07

    A first solution is to use X-Frame-Options header to prevent loading your page to an iframe. X-Frame-Options can specify one of two values: SAMEORIGIN, which only allows iframes from the same origin to display this content, and deny, which prevents any iframe from doing so. BUT this header is not part of HTTP specification and was introduced by Microsoft, so not all browsers support this header. An example of X-Frame-Options:

    X-Frame-Options: SAMEORIGIN
    

    In case some old browsers don't support the X-Frame-Options header. You could try a technique called FrameKiller. There are limitations, though, as pointed out in that link.

    The user agent does not support JavaScript.

    The user agent supports JavaScript but the user has turned support off.

    The user agent's JavaScript support is flawed or partially implemented.

    The idea is to use javascript to detect whether your page is loaded into an iframe. There are many ways to implement a frame killer script.

    For your requirement, you could implement a frame killer script like this: try to access your parent window to read the window.location. If they include your page inside their iframe, the code would throw exception (cross-domain)

    Example code:

    window.onload = function(){
       try
       {
           if (window.parent && window.parent.location.hostname !== "www.abc.com"){
              throw new Error();
           }
       }
       catch (e){
          alert("Please visit www.abc.com to play this game.");
          //You could do whatever you want here
       }
    }
    

提交回复
热议问题