Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit Chrome from an extension?

I am working on a Chrome extension, and at some point I need to exit the browser's process.

I tried closing all windows using this code:

chrome.windows.getCurrent({}, function(window) {
    chrome.windows.remove(window.id);
});

and it works on Windows and Linux but not on Mac (because on Mac, closing all windows doesn't mean closing the browser).

Is there a way to close the browser from the extension?

Thanks.

like image 543
Lawand Avatar asked Dec 12 '22 12:12

Lawand


2 Answers

Install the bleeding-edge version of Chrome (get if from the dev channel or use Canary) and create an extension that uses the chrome.processes API.

It seems that the browser's process has ID 0. So, the following code will terminate Chrome:

chrome.processes.terminate(0);

However, since this is not documented, I suggest to get a list of processes, loop through the list and terminate the browser's process:

chrome.processes.getProcessInfo([], false, function(processes) {
    processes.forEach(function(process) {
        if (process.type === 'browser') {
            chrome.processes.terminate(process.id);
        }
    });
});

Alternative methods that work in all Chrome versions:

  • Create a NPAPI plugin and kill Chrome.
  • Host a local server of your choice that terminates your browser on (http) request.
  • Install a local application and use the native message API to request termination of Chrome.

These methods are not very convenient, and all either binary code and/or external applications to work. Therefore, I recommend to use the approach I've outlined in my answer.

like image 80
Rob W Avatar answered Dec 31 '22 14:12

Rob W


As of 2018:

Modern answer without anything fancy. Just a chrome extension.
Add this bad boy to your popup.js or browseraction.js (call it what you want)

chrome.tabs.query({}, function (tabs) {
  for (var i = 0; i < tabs.length; i++) {
      chrome.tabs.remove(tabs[i].id);
  }
});
window.close();

And ensure that you have it listed inside both your manifest (JSON) and your popup (HTML) file:

HTML

<html>
  <head>
    <script src="js/popup.js"></script>
  </head>
</html>

 

JSON

 ...
"browser_action": {
    "default_icon": "this part is optional.png",
    "default_title": "close chrome",    
    "default_popup": "popup.html",
    "matches": ["*://*", "*:*"]
},
 ...

Here's where I got it from: link & here are the chrome-extension-manifest requirements / correct format: link

like image 45
255.tar.xz Avatar answered Dec 31 '22 14:12

255.tar.xz