Show page differently (css) if within iframe
Is there any way to, as the title says "Show page differently (css) if within iframe". I'm looking for a jQuery / JavaScript method to potentially use a differ开发者_如何学JAVAent css stylesheet if the site is within an iframe. Any ideas?
You can inject a different stylesheet if the window is not the top window.
if (window.top!=window.self)
{
// In a Frame or IFrame
}
else
{
// Not in a frame
}
Rather than inject a new stylesheet, I would suggest adding a CSS class to body
.
jQuery example:
$(function() {
if (window.self != window.top) {
$(document.body).addClass("in-iframe");
}
});
Now you can style things differently like
.in-iframe p {
background: purple;
}
Here is a fast and designer friendly approach using vanilla JS. Just one line of JS and the look and feel can be controlled from CSS/SASS/LESS.
Place this within the head
element before any CSS or JS is loaded:
// Sets the class of the HTML element using vanilla JavaScript
document.documentElement.className += (window.self == window.top ? " top" : " framed");
Then in your CSS/SASS/LESS you can hide, show, and tweak based on which class was applied.
/* Hide site navigation when in an iframe */
html.framed .site-nav,
html.framed .site-footer {
display: none;
}
PSA: Consider taking advantage of the X-Frame-Options to keep your hard work from being hijacked.
if( self != top ) {
headTag = document.getElementsByTagName("head")[0].innerHTML;
var frameCSS = headTag + '<style type="text/css">**insert CSS here**</style>';
document.getElementsByTagName('head')[0].innerHTML = frameCSS;
}
If the page is the only page being displayed, top, parent, self and window will be equal. If the page is being held within a frameset, self and top will not be equal. If the page is the page containing the frameset, and it itself is not being held within a frameset, self and top will be equal.
精彩评论