Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i check if the current window is "top" (or "parent") via php?

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.

like image 508
Lucas Matos Avatar asked Dec 02 '22 00:12

Lucas Matos


1 Answers

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.

like image 178
Bojangles Avatar answered Dec 04 '22 10:12

Bojangles