Is there a way to check if my web page has been loaded inside another site’s frames, and if so get rid of them?
Yes, you can use JavaScript to determine if your page is enclosed in a frame, and if that turns out to be the case reload your document outside the frame. “Q473 Is it possible for a script to check for frames and if present, get rid of them?” by irt.org shows us that we can compare the objects parent and self to determine if an encasing frame is present. If the results of that check are true, we then kill the frame by reloading our document’s location as the top-most content.
window.onload = function() {
if (parent != self)
top.location.href = document.location.href;
}
Keep in mind…
- Sites such as Facebook enclose external links in a frame to engage visitors — their navigation bar lets members re-share and comment on your site. Eliminating that navigation bar prevents you from benefiting from this sort of activity.
- There is no telling if a site such as Facebook may penalize or blacklist sites that interfere with their frames.
- This code may increase bandwidth usage by adding a second page load. See below for advice on reducing the effect.
Reduce the effect of this script on bandwidth usage
This code waits for the entire page and its contents to load, checks to see if a frame is present and if so reloads the document without the frame. This causes your page to load twice, which (browser caching aside) means possibly double the impact on your bandwidth usage. This also means your visitor must wait for every piece of content to load, which could be an unnecessarily long time if bandwidth-heavy content (e.g. large images) is present.
If this is a concern for you, try checking when the DOM is ready instead of waiting for everything, images and all, to load. You can write your own function to check for DOM readiness, or use a JavaScript framework that contains such a check. For example, here it is done with jQuery:
$(document).ready(function() {
if (parent != self)
top.location.href = document.location.href;
});
I do not recommend adding an entire JavaScript framework to your site just to break out of frames. The overhead of serving the framework’s code for this one simple task would probably defeat its very purpose. But if you are already using a JavaScript framework for other functionality, you don’t have to re-invent the wheel with your own DOM readiness checker.




