Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid loading my site in iFrame

To avoid XRS, I would check where my site load, in the main window or in frame or iframe. Is it possible to check on server side from where request, that is a browser address line or src attribute of frame or iframe. If is not possible on server side, then how is possible with jQuery? Thanks for help.

like image 832
flap13 Avatar asked Dec 31 '25 12:12

flap13


1 Answers

Use a frame killer.

CSS:

<style>
html{display:none;}
</style>

Javascript:

<script>
function frameKiller() {
    if (self == top) {
        document.documentElement.style.display = 'block';
    } else {
        top.location = self.location;
    }
}
</script>

Then call the framekiller function on the pages you want to protect

Jquery:

$(function () {
    frameKiller();
});

Complete Example:

<!DOCTYPE html>
<head>
<title>Page Title</title>

<style>
html{display:none;}
</style>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

</head>

<body>

Page Content

<script>
function frameKiller() {
    if (self == top) {
        document.documentElement.style.display = 'block';
    } else {
        top.location = self.location;
    }
}

$(function () {
    frameKiller();
});
</script>

</body>

</html>

To test, try to load this page into an iframe from a different domain.

like image 89
Patriotec Avatar answered Jan 03 '26 02:01

Patriotec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!