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

后端 未结 3 1674
甜味超标
甜味超标 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:03

    Doing this via JavaScript is limited in how it will restrict the content to the browser level. You might be better off Apache mod_rewrite to more effectively block content on a server level as explained here.

    For example, this code you could place in an .htaccess file if your server supports it. I am using www.abc.com as an example & matching swf & fla files as an example:

    RewriteCond %{HTTP_REFERER} !^$
    RewriteCond %{HTTP_REFERER} !^http://(www\.)?abc.com/.*$ [NC]
    RewriteRule ^.*\.(swf|fla)$ - [F] 
    
    0 讨论(0)
  • 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
       }
    }
    
    0 讨论(0)
  • 2021-02-06 15:13
    if (window.top != window.self) {
                    window.top.location = window.self.location;
                }
    

    It first checks that the top most frame is the frame itself or not if it is not it changes the top level frame to this one. it is javascript.

    0 讨论(0)
提交回复
热议问题