Search code examples
javascriptfirefox-addonbrowser-extension

Firefox extension - How to show text to user from background script?


This may be a very basic question, but I can't find an answer on the internet. What I'm trying to do, is showing the user some text after clicking on a context menu item. I first thought about using alert() but then realized, that this isn't possible in background scripts. Is there any alternative way to show some text to the user? Any ideas would be appreciated.

My background.js file:

browser.contextMenus.create({
    id: "showtext",
    title: "Show text",
    contexts: ["selection"]
});

browser.contextMenus.onClicked.addListener(function (info, tab) {
    switch (info.menuItemId) {
        case "showtext":
            {
                console.log(info.selectionText);
                // alert() doesn't work here
                // looking for alternative
            }
    }
});

FYI: I'm trying to create a little encryption and decryption tool.

PS: I'm a beginner in extensions. :(


Solution

  • You could insert elements into the page:

    const node = document.createElement('div');
    node.textContent = "This page has been eaten";
    document.body.appendChild(node);
    

    Style it as needed for it to appear however you need.

    MDN: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Modify_a_web_page