Search code examples
javascripthtmlbrowser

Prevent window.close after redirect to a custom protocol URL


I need to redirect a page to an URL, using a custom protocol, to open a local application. After the redirection is done and the application is called, the page needs to be closed using window.close() function.

If the protocol of the redirection is not recognized, nor the user explicitly allowed this protocol, an warning popup is presented by the browser (not my code), informing the not recognized protocol and asking the user to confirm the opening of the application.

enter image description here

The user also have the option of click in "always allow" (the explicity consent) to prevent the warning popup be presented in the next time.

My original code is this:

<html>

<head>
    <script src="https://code.jquery.com/jquery-3.7.1.slim.js"
        integrity="sha256-UgvvN8vBkgO0luPSUl2s8TIlOSYRoGFAX4jlCIm9Adc=" crossorigin="anonymous"></script>
</head>

<script>
    $(document).ready(function () {
        window.location = "custom_app_protocol://commands/goto?some_parms";
        window.close();
    });
</script>
<body>
    Redir test.
</body>
</html>

This code above works fine if the warning popup is not presented (protocol recognized or explicit consent already given). Then, the application is called and the page is closed.

But, if the warning popup is presented, the page is closed without perform the app call.

An option would be include a timeout after the call:

$(document).ready(function () {
    window.location = "custom_app_protocol://commands/goto?some_parms";
    setTimeout(function () {
        window.close();
    }, (5000));
});

But, if the user doesn't click in the warning popup before the timeout trigger the page closing command, the page will be closed without open the app.

So, my question is: there is an way to perform the window.close() only after the warning popup is closed?


Solution

  • Try this:

    $(document).ready(function() {
        $(window).on("focus", function() {
            window.close();
        });
        window.location = "custom_app_protocol://commands/goto?some_parms";
    });
    

    The "choose an app" dialog takes away focus from the window. When the user makes a choice, the window will regain focus, and then you close it.

    I've tried it locally and it seems to work well, not sure if some edge case will not be covered but you can try.