How to focus on a previously opened window using w

2019-08-10 23:21发布

问题:

I would like to open a popup window for a website and keep it for a music player to be able to play seamless music while the user is navigating across pages.

What I would like to achieve is that when the user first clicks the "Music" button a new popup window opens using window.open (done). The second part would be that when the user navigates to other pages and clicks again on the "Music" button then the already open window receives the focus but doesn't load again.

However what is happening is that as soon as the user navigates away from the original page then the browser forgets that the window has been opened and the focus() stops working. It seems that focus() works as far as the user is staying on the same page.

I have found a similar question and tried to implement my code based on that question:

JavaScript window.open only if the window does not already exist

Here is the code I have written so far:

$('a.music').click(function(){
        if(typeof(winRef) == 'undefined' || winRef.closed){
            winRef = window.open(this.href,'Music','left=20,top=20,width=500,height=500,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,titlebar=0');
        } else {
            winRef.focus();
        }
        return false;
    });

Here is the live site if you would like to have a look. http://ilhaamproject.com/

How should I reference the opened window such that it works across different page-loads?

回答1:

Edit: I take my earlier answer back. This can be done. Just have the opened window set winRef on its opener. In your popup window, put this code:

setInterval(function()
{
    opener.winRef = window;
}, 500);

That's it!

There may be some event you can hook on the opener window so you don't have to use the setInterval, but I'm not sure.


Original answer:

You cannot - JavaScript variables are gone after the script's page is unloaded. The only way you could do this would be to not unload the page that opened the popup. You can keep the page open, but change its content using AJAX. Or you can use the frames technique I suggested for a similar question last week.