Search code examples
javascriptfirefox-addon-webextensions

How to close a window opened using browser.windows.create()?


I cannot find any questions/answers that address this issue. Sorry if I have missed something.

I am just getting started with WebExtensions. I have a form that is displayed in a window that I open in my background.js script using windows.create();. I cannot figure out how to close that window (other than manually clicking the close box). The window is created and correctly displays my form. I can even submit the form. But I cannot get the window to close. I have even tried injecting a content script into the form page - I cannot close it from there either. I have tried attaching a handler to the click event of a button, with no luck.

It is my understanding that only the script that creates the window can close it. But I cannot figure out, or find by searching online, how I would do that in my browserAction background script (which is where the window is created)?

I am running Firefox 51 on Debian.

Here is the code that creates the window.

background.js

var formUrl = 'http://example.com/api/test'
chrome.browserAction.onClicked.addListener(
  function(tab)
  {
    chrome.tabs.query({"active": true, "currentWindow": true}, function(tabs) 
      { 
      var target = tabs[0].url;
      if (target.substr(0,4) == 'http')
      {
        var encUrl = escape(target);
        var newUrl = formUrl + '?default=' + encUrl;
        w = chrome.windows.create({
          url: newUrl,
          width: 775,
          height: 350,
          type: 'popup'
        });
      }
      else
      {
        console.log("Only http(s) pages can be processed at this time.");
      }
    });
  }
);

Solution

  • The API call windows.remove() is specifically for closing a window. You will need the windowId, which is available as the id property within the windows.Window Object which is passed to the callback/resolve function for windows.create().

    You do not need to call windows.remove() from the same script which opened the window. Any script with access to that API can close the window.