I need to display a link if the current page is being viewed in parent browser window, or display another link if window is being viewed inside an iframe. How can i do that via php? Something like:
if (self == top)
echo '<span><a href="./" >Link1</a></span>';
else
echo '<span><a href="./index.php">Link2</a></span>';
edit: since it cant be done with php, i still looking for similar solution, maybe JS, can someone pls tell me how?
Final edit: The answer:
echo '
<script type="text/javascript">
if(window === top) {
document.write("<span><a href=\"./\">go-to-frame</a></span>");
}
else {
document.write("<span><a href=\"./index.php\">go-to-top</a></span>");
}
</script>
';
thank you all.
You can't do this with PHP; it's a server side language, not a client side one. Because it's up to the client how it handles windows, the server doesn't know anything about this. You could send something back in an AJAX request then reload the page, but this is a messy, horrible solution.
To detect if you're in the top level window, you need to do this:
if(window.top == window.self) {
// Top level window
} else {
// Not top level. An iframe, popup or something
}
You were very close with the example you gave in your question. window.top
is the top-most window of the stack, and window.self
is the window the current JS and DOM is in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With