Modifying a Selection

I am attempting to write a context menu that will apply tags to selected text.

I have the whole menu structure thing down, and based on some coding observations, this should work, it’s very proof of context now, but it does not.

I have this function:
function getSel() // javascript
{

    // obtain the object reference for the textarea>
    var txtarea = document.getElementById("mytextarea");
    // obtain the index of the first selected character
    var start = txtarea.selectionStart;
    // obtain the index of the last selected character
    var finish = txtarea.selectionEnd;
    //obtain all Text
    var allText = txtarea.value;
    // obtain the selected text
    var sel = allText.substring(start, finish);
    //append the text;
    var newText=allText.substring(0, start)+"[b]"+sel+"[/b]"+allText.substring(finish, allText.length);
        txtarea.value=newText;
    // do something with the selected content
}

This should apply the and tags to the selected text.

It is invoked by this menu selection: (other test menu functions omitted)

browser.menus.onClicked.addListener((info, tab) => {
    switch (info.menuItemId) {
.
.
.
        case "bbCode_Bold":
            getSel();
            break;

Why is this not tagging the selected text?

The problem here is that the background page is a different HTML context than the page that the context menu is triggered in. To change the page you need to use a content script.

Further, to find out why something is not working, I can really recommend https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Debugging

1 Like