Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening chrome extension in new tab when toolbar icon is clicked

I want the extension HTML to open in a new tab rather than in a popup. An existing extension, Session Buddy, has the exact behaviour that I'm looking to replicate.

The issue is that Chrome opens new extension tabs nonstop after I click on the toolbar icon, when the desired behaviour is (obviously) to have just one tab open. Strangely, I can get just one tab to open when I use a "web URL" such as https://stackoverflow.com/.

manifest.json:

{
    "manifest_version": 2,
    "name": "angular chrome extension boilerplate",
    "version": "1.0.0",
    "background": {
        "scripts": ["background.js"],
        "persistent": true
    },
    "permissions": [
        "activeTab",
        "tabs",
        "background"
    ],
    "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}

background.js:

chrome.tabs.create({ url: chrome.extension.getURL('index.html') });

Several posts on this site have a similar question but none of the suggested solutions worked for me:

  • Chrome Extension: onclick extension icon, open popup.html in new tab: When I use event pages or add a listener to the onClicked even, nothing happens when I click the extension toolbar icon.
like image 667
GreatHam Avatar asked Dec 09 '25 17:12

GreatHam


1 Answers

It turns out that the right way to get a tab to open upon clicking the toolbar icon is to wrap the call to chrome.tabs.create() in an onClicked listener:

Revised background.js:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.create({ url: chrome.extension.getURL('index.html'), selected: true });
});

Initially this will not work due to chrome.browserAction.onClicked being undefined. To solve this, one needs to add an empty "browser_action" object to manifest.json. Also, the previously used persistent background and activeTab permission are unnecessary and can be removed:

Revised manifest.json:

{
    "manifest_version": 2,
    "name": "angular chrome extension boilerplate",
    "version": "1.0.0",
    "browser_action": { },
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "permissions": [
        "tabs",
        "background"
    ],
    "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}
like image 198
GreatHam Avatar answered Dec 14 '25 00:12

GreatHam