3

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:

GreatHam
  • 1,656
  • 3
  • 16
  • 21
  • 1
    Put it inside a click listener for the icon: [sample](https://developer.chrome.com/extensions/examples/api/browserAction/make_page_red/background.js). – wOxxOm Dec 16 '17 at 01:45
  • The tab doesn't open if I put `chrome.tabs.create()` inside a click listener. – GreatHam Dec 16 '17 at 01:49
  • 1
    It's time to [debug the background script](https://stackoverflow.com/a/10258029)! – wOxxOm Dec 16 '17 at 01:51

1 Answers1

7

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'"
}
GreatHam
  • 1,656
  • 3
  • 16
  • 21
  • This is working fine but opening multiple tabs on subsequent clicks. How can I prevent this? – san Dec 18 '21 at 06:56
  • The `selected` property is now deprecated. Use `active` instead. Also, the `chrome.extension.getURL()` function is deprecated and one should use `chrome.runtime.getURL()` instead. – Volomike Apr 19 '22 at 02:11
  • Also, in Manifest V3, replace `chrome.browserAction` with `chrome.action`. – Volomike Apr 19 '22 at 02:14