Return Focus to the window that opened the popup

Asked

Viewed 785 times

0

I have the following code that opens a window popup janela.php where I receive some data from the database:

<script>
$("button").click(function(){
    window.open("janela.php", "_blank", "width=400, height=500");
});
</script>

In the window popup open, there is a button where the user clicks to send data to the main window (opener), the one that opened the popup:

<script>
$(".botao").click(function(){
    // outros códigos aqui que não vem ao caso
    $(window.opener.document).find("#status").text("Salvo!");
});
</script>

Everything works perfectly.

Doubt: how to do that by clicking the button .botao in popup, the phocus pass from popup to the main window (opener)? That is, by clicking the button, the popup move to the background and window opener focus on the screen.

Would need something crossbrowser, that works in browsers Chrome, Firefox, Safari, Opera, IE (at least no 11) and Edge.

  • You can add focus with .focus(), but it is not possible to minimize the open window (at least Chrome). https://developer.mozilla.org/en-US/docs/Web/API/Window/open#Note_on_use_of_window_open

  • I tried but it didn’t work.

  • 2

    I believe that doing this with Javascript is not possible. A possible alternative would be to create a custom modal on the page...

3 answers

0

An alternative would be for you to perform all the necessary actions and then perform a Blur, one phocus in the field status and finally close the popup.

$(".botao").click(function () {
    //...
    window.opener.$("#status").val("Salvo!");

    window.opener.$("#status").blur();
    window.opener.$("#status").focus();
    window.close();
});

However, in this case, you will be forced to close the popup and need to choose a field from the main window that will receive the focus.

I found a topical regarding "minimize" or change the focus between popups and parent window via Javascript but apparently this is not possible.

0

Disclaimer: I don’t have enough points to comment, so I’m answering here.

Test the following code by running along with your already done

<script>
$(".botao").click(function(){
$(window.opener.document).find("#status").text("Salvo!");
window.opener.focus(''); // joga o foco para janela que abriu a popup  
window.blur(); // tira o foco da popup
}
</script>

0


I found a solution for the mentioned browsers (speaking of more modern browsers, in April/2018).

Before, it is necessary to set a name to main window (opener), whichever name. Just put in the main window script:

<script>
name = "principal";
</script>

And the code in popup for browsers:

- IE 11, Edge, Safari:

window.open('', window.opener.name);

- Chrome, Opera, Safari:

window.opener.focus();

- Firefox:

Only works with both lines at the same time:

window.open('', window.opener.name);
window.opener.focus();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.