window.opener.focus() doesn't work

前端 未结 4 1950
旧时难觅i
旧时难觅i 2020-12-04 01:55

I can\'t seem to get this to work.

In response to a click, window A opens window B (which then has focus). Then, in response to a click on B, the window calls

4条回答
  •  隐瞒了意图╮
    2020-12-04 02:09

    I can see why a browser/OS will not allow a child windows to take over the focus (abuse of power). Here is a workaround:

    1. In the parent window, declare a function in "window.external" that will trigger Javascript "alert()" or "confirm()".
    2. Invoke that function from the child window.
    3. The browser might ignore a request from a child window that wants to control the focus (e.g. window.opener.focus()), but the browser should honor a request from a parent window that triggers an alert() or a confirm() action, which requires to focus on the parent window.

    JS Parent:

        var child = window.open('child.html', 'child');
        window.external.comeback = function() {
            var back = confirm('Are you sure you want to comback?');
            if(back) {
                child.close();
            } else {
                child.focus();
            }
        }
    

    JS Child:

        // assuming you have jQuery
        $('.btn').click() {
            window.opener.external.comeback();  
        };
    

    --I am using this code in a real world application to handle a checkout request that runs in child window, and I need to gracefully return to the parent window.

    See: SimplifySites.com

提交回复
热议问题