Reputation: 6947
I have a Chrome extension which needs to be open only in one window per machine at a time. What would be the best way to enforce this condition? For example, is there a mechanism to point the user to an existing tab running the extension, if there exists such a tab?
The relevant parts of my manifest file are as follows:
manifest.json
{
"manifest_version": 2,
"browser_action": {
"default_icon": "/img/favicon.ico",
"popup": "main.html"
},
"background": {
"scripts": ["open.js"]
}
}
And the open.js
reads as follows:
open.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.create({'url': chrome.extension.getURL('test.html')}, function(tab) {
});
});
Upvotes: 2
Views: 2601
Reputation: 1137
Update Updated to also include focusing on a tab that is in a different window
Since no one posted the answer to this question here it is, taken from Rob W's github as linked in the comments under the question https://github.com/Rob--W/stackexchange-notifications/blob/8947b9982cd7b9e04ccf0ef23510571f39d33c4e/Chrome/using-websocket.js#L66-L82.
This is a more basic version replacing the openTab() function found in the original code with the basic command to open a new tab.
var options_url = chrome.extension.getURL('options.html');
chrome.tabs.query({
url: options_url
}, function(tabs) {
if (tabs.length == 0) {
chrome.tabs.create({ url: "main.html" });
} else {
// If there's more than one, close all but the first
for (var i=1; i<tabs.length; i++)
chrome.tabs.remove(tabs[i].id);
// And focus the options page
chrome.tabs.update(tabs[0].id, {active: true});
chrome.windows.update(tabs[0].windowId, {focused:true})
}
});
Upvotes: 3