user3425506
user3425506

Reputation: 1437

Firefox add-on: Open new tab by clicking on custom menu item

I have made a Firefox add on with the following code in background.js

browser.menus.create({
    id: "q-menu-item",
    title: "'%s' redirect",
    contexts: ["selection"],
});

browser.menus.onClicked.addListener((info, tab) => {
    console.log(info.selectionText);
    window.open("http://www.google.com/", '_blank').focus();
});

and manifest.json:

{
    "manifest_version": 2,
    "name": "add-on-q",
    "version": "1.0",
  
    "description": "Context menu item opens new tab",
  
    "background": {
      "scripts": ["background.js"]
    },

    "permissions": [
      "menus"
    ]

  }

When I install the add on and select some text and then right click I do get a custom menu item as expected. However when I click on it, it does not open a new tab at address "google.com" as expected although the selected text is logged to the console. I would also like to use window.location.href = 'http://www.google.com'; but that did not work either.

I have read quite a lot of MDN's documentation on this but am quite confused by it. Some pointers would be very useful.

Upvotes: 2

Views: 43

Answers (1)

Nanigashi
Nanigashi

Reputation: 393

Although the extension's background context has a window object, several methods do not work. To operate on windows or tabs from a background script, use browser.windows or browser.tabs. So don't use something like:

open( 'https://www.google.com/', '_blank' ).focus();

To create a new, focused window, use something like:

browser.windows.create( {
  url: 'https://www.google.com'
} );

Unlike open, windows.create bypasses the browser setting "Block pop-up windows" on the "Privacy & Security" tab and the browser setting "Open links in tabs instead of new windows" on the "General" tab. It really does create a new window.

To create a new, active tab in the current window, use something like:

browser.tabs.create( {
  url: 'https://www.google.com'
} );

Neither method requires permissions.

Upvotes: 0

Related Questions