Search code examples
javascriptgoogle-chrome-extensionfirefox-addon-webextensionscontent-script

Open options page from content-script on button click?


I am trying to open my web-extension options page from an injected button via a content-script onto a page. Here is the setup:

manifest setting:

"options_ui": {
    "page": "options/options.html",
    "open_in_tab":true
},
"web_accessible_resources": ["icons/icon.png", "icons/icon64.png","options/options.html"]

content-script.js:

<a href="moz-extension://1f82d05-3abf-4bea-80e2-db87e97486d3/options/options.html" target="_blank">Settings</a>

What am I missing here? Also, I know moz-extension: might not be the best option for cross-browser operation but not sure what should be the correct namesapce?

EDIT:

I am using a fixed id in manifest as :

"applications": {
        "gecko": {
            "id": "{adacfr40-acra-e2e1-8ccb-e01fd0e08bde}"
        }
},

Solution

  • Your content script, as shown, is actually a chunk of HTML and not JavaScript, as expected. So it wouldn't work. Perhaps that's not your actual code, just what you create?

    But suppose you do adjust the content script to add a button and have a listener attached (out of scope for this question, I think). How to open the options page?

    The canonical way is to call browser.runtime.openOptionsPage(), but that API can't be called from a content script.

    Two options:

    1. Stick with openOptionsPage(). In that case, you need a background (event) page that listens to Messaging, and then signal from the content script that you want the options page open.

      The advantage of this approach is that you don't need to make the options page web-accessible.

    2. If you insist on directly opening the page from the content script / a tag, you can, but you'll need to get the dynamically-allocated UUID for your extension instance.

      The URL for your options page is not fixed, but should be obtained with browser.runtime.getURL("options.html"), and that URL should be used in the link creation.

      This method requires declaring it as web-accessible.