Canna
Canna

Reputation: 3804

How to close the browser tab(parent window) with JavaScript

scenario I want:

A user presses a button, this button makes an alert box, user presses cancel button, the action closes the browser tab

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>My page</title>

        <style>
            .bootbox-close-button.close{
                display: none;
            }
            .btn-primary{
            }
        </style>
        <!-- CSS dependencies -->
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    </head>
    <body>

        <p>
            Content here. <a class="alert" href=#>Alert!</a>
        </p>

        <!-- JS dependencies -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="js/bootstrap.min.js"></script>

        <!-- bootbox code -->
        <script src="js/bootbox.min.js"></script>
        <script>
            $(document).on("click", ".alert", function(e) {
                bootbox.dialog({
                    message : "I am a custom dialog",
                    title : "Custom title",
                    buttons : {
                        ok : {
                            label : "OK",
                            className : "btn-primary"
                        },
                        cancel : {
                            label : "Cancel",
                            className : "btn-default",
                            callback : function() {
                                                /*NEED TO HANDLE CLOSE IN THIS PLACE*/
                                window.parent.close();
                            }
                        }
                    }
                });
            });
        </script>
    </body>
</html>

I made like this, and if I press close it says,

Scripts may close only the windows that were opened by it.

Is it possible to close the parent window?

Upvotes: 1

Views: 7333

Answers (2)

Mike M
Mike M

Reputation: 752

You cannot close a window which you did not create. In other words, a javascript script only has permissions to close the ones that it creates itself.

Duplicate post

Upvotes: 0

Phlume
Phlume

Reputation: 3131

I'm pretty sure you can close a newly opened window with window.close() syntax, but this will only affect windows that were also opened by the same script in some browsers (https://developer.mozilla.org/en-US/docs/Web/API/window.close?redirectlocale=en-US&redirectslug=DOM%2Fwindow.close)

Also, this may be a duplicate of this page: JavaScript/ jquery for Closing Browser FireFox / chrome / IE

Upvotes: 2

Related Questions