Search code examples
javascriptjquerygoogle-chromegoogle-chrome-extensionwindow

Check if window is already open from a non-parent window (chrome extension)


I am making a Chrome extension. Clicking a button in popup.html opens a new window and loads feedback-panel.html.

This works but, on click, I'd like to check if the window is already open and if so focus to it instead of creating a new one.

JavaScript window.open only if the window does not already exist looked promissing but it relies on the open windows being stored as variables on the parent page when the window is opened and checking those before opening a new one. This wont work for me since the parent window (popup.html) will often be closed and reopened itself and I'd lose the variables.

I tried to implement the same idea but store the window variables in with chrome.storage since it lets you store objects. Well, it does let you store objects but it serializes them first so the window variable loses all of it's functions and I end up with

result.feedbackPanel.focus() is not a function

Here is my attempt:

function openFeedbackPanel(){
    chrome.storage.local.get('feedbackPanel', function (result) {
        console.log( result.feedbackPanel); // logs window object sans all functions
        if(result.feedbackPanel && ! result.feedbackPanel.closed){
            try{
                result.feedbackPanel.focus();
            }
            catch(error){
                chrome.storage.local.remove('feedbackPanel', function () {
                });
                createFeedbackPanel();
            }
        }
        else{
            createFeedbackPanel();
        }
    });
}
function createFeedbackPanel(){
    var win =  window.open('feedback-panel.html', 'Feedback', 'width=935, height=675');
    console.log(win); // logs full object as expected 
    chrome.storage.local.set({"feedbackPanel": win});
}



$('#some-button').click(openFeedbackPanel());

So, since this doesnt work:

How can I check if a popup window is already open from a non-parent window (one that did not open the popup)?


Solution

  • no need to track windows and store them.
    if you know your extension ID, the simplest way is to test all tabs url's and see if it's already opened

    chrome.tabs.query({}, function(tabs) {
      var doFlag = true;
      for (var i=tabs.length-1; i>=0; i--) {
        if (tabs[i].url === "chrome-extension://EXTENSION_ID/feedback-panel.html") {
          //your popup is alive
          doFlag = false;
          chrome.tabs.update(tabs[i].id, {active: true}); //focus it
          break;
        }
      }
      if (doFlag) { //it didn't found anything, so create it
        window.open('feedback-panel.html', 'Feedback', 'width=935, height=675');
      }
    });
    

    and here is already answered how to get extension ID,