Hide header if in iframe

2019-03-04 10:13发布

问题:

I need to hide the header of my wordpress-based website, in case the site is loaded in an iFrame. Should I do it with javascript, in functions or in css? And how can I do it? I found this

<script type="text/javascript">
   var isInIFrame = (window.location != window.parent.location);
   if(isInIFrame==true){
       alert("It's in an iFrame");
       document.getElementById('header').style.display = "none";
       }
   else {
       alert("It's NOT in an iFrame");
       }
   </script>

But I don't where to put it (and also I don't know if it could work). I hope someone can help me, thanks!

回答1:

I grabbed this code (and modified it for your use) from this post so go there and give Greg an upvote :) How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

function inIframe() {
    try {
        return window.self !== window.top;
    } catch () {
        return true;
    }
}

if(inIframe){
    document.getElementById('header').style.display = "none"; //if you want javascript only
    $("#header").hide(); // if you want jquery
}

However this will only work if the header has the ID "header".