Google Chrome Extensions: create a window only once.

I open a new window by clicking on the extension button next to the search bar. I would like to open a new window only if it is not already open; in this case, I would rather show the old one.

Here is my code, but it does not work.

var v = null; var vid = null; chrome.browserAction.onClicked.addListener(function(tab) { chrome.windows.getAll({}, function(list) { // check if already exists for(window in window_list) if(window.id == vid) { window.focus(); return; } chrome.windows.getCurrent(function(w) { v = chrome.windows.create({'url': 'my_url', 'type': 'panel', 'focused': true}); vid = w.id; }); }); }); 

Can someone explain to me how to fix this?

Most likely, after closing the application, the v and vid values ​​are deleted (after the script is finished), but how can I fix it? If possible, without using localStorage or cookies.

I tried to specify the tabId properties when creating the window, but this will not work. I also tried using the chrome.windows.onRemoved.addListener functionality, but it does not work either.

+4
source share
2 answers
  • Change window to a different variable name .
  • Be consistent in variable names. window_list and list are two different things.
  • Use chrome.windows.update instead of window.focus() because the latter does not work.
  • Use chrome.windows.get to see if a window exists, and not maintain a list of windows.
  • Details of the new window are available in the chrome.windows.create . Use this method correctly:

the code:

 chrome.windows.get(vid, function(chromeWindow) { if (!chrome.runtime.lastError && chromeWindow) { chrome.windows.update(vid, {focused: true}); return; } chrome.windows.create( {'url': 'my_url', 'type': 'panel', 'focused': true}, function(chromeWindow) { vid = chromeWindow.id; } ); }); 

Or instead of checking if a window exists, just refresh the window, and if an error occurs, open a new one:

 chrome.windows.update(vid, {focused: true}, function() { if (chrome.runtime.lastError) { chrome.windows.create( {'url': 'my_url', 'type': 'panel', 'focused': true}, function(chromeWindow) { vid = chromeWindow.id; }); } }); 
+5
source
 chrome.windows.getAll({}, function(window_list) { var extWindow = ''; window_list.forEach(function(chromeWindow) { //Check windows by type if (chromeWindow.type == 'panel') { extWindow = chromeWindow.id; //Update opened window chrome.windows.update(extWindow, {focused: true}); return; } }); if (extWindow == '') { //Open window chrome.windows.create( { 'url' : 'my_url', 'type' : 'panel', 'focused' : true }, function(chromeWindow) { extWindow = chromeWindow.id; } ); } }); 

This is alternative code that works for me

-1
source

Source: https://habr.com/ru/post/1401191/


All Articles