How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

前端 未结 16 2387
攒了一身酷
攒了一身酷 2020-11-22 00:28

I am writing an iframe based facebook app. Now I want to use the same html page to render the normal website as well as the canvas page within facebook. I want to know if I

16条回答
  •  遥遥无期
    2020-11-22 01:06

    Use this javascript function as an example on how to accomplish this.

    function isNoIframeOrIframeInMyHost() {
    // Validation: it must be loaded as the top page, or if it is loaded in an iframe 
    // then it must be embedded in my own domain.
    // Info: IF top.location.href is not accessible THEN it is embedded in an iframe 
    // and the domains are different.
    var myresult = true;
    try {
        var tophref = top.location.href;
        var tophostname = top.location.hostname.toString();
        var myhref = location.href;
        if (tophref === myhref) {
            myresult = true;
        } else if (tophostname !== "www.yourdomain.com") {
            myresult = false;
        }
    } catch (error) { 
      // error is a permission error that top.location.href is not accessible 
      // (which means parent domain <> iframe domain)!
        myresult = false;
    }
    return myresult;
    }
    

提交回复
热议问题