Text selection and display in context menu chrome extension

前端 未结 1 588
迷失自我
迷失自我 2020-12-12 17:43

I have been working on a small Chrome extension with a problem I cant seem to get my head around and would appreciate someone to look at it with a fresh perspective.

相关标签:
1条回答
  • 2020-12-12 18:18

    UPDATE

    I just looked at the docs and all this can be done much more simpler without any content scripts and callbacks:

    chrome.contextMenus.create({
        title: "Test %s menu item", 
        contexts:["selection"], 
        onclick: function(info, tab) {
            sendSearch(info.selectionText);
        }
    });
    

    That's all you need, because you can use %s in menu title to get selected text.

    (everything below is not needed anymore)


    Your getSelection() method doesn't return selected text, it just injects a content script to a page. Selected text is received sometime later in onRequest and then passed to a callback function from your callback array as a parameter.

    So this part:

    var tx = getSelection();
    var title = "Test '" + tx + "' menu item";
    var id = chrome.contextMenus.create({"title": title, "contexts":[selection],
                                       "onclick": sendSearch(tx)});
    console.log("selection item:" + id);
    

    needs to be changed to something like this:

    getSelection(function(tx) { 
        var title = "Test '" + tx + "' menu item";
        var id = chrome.contextMenus.create({"title": title, "contexts":["selection"],
                                           "onclick": sendSearch(tx)});
        console.log("selection item:" + id);
    })
    

    But I would get rid of that selection_callbacks array altogether as I think it is not needed:

    chrome.extension.onRequest.addListener(function (request) { 
        var tx = request;
        var title = "Test '" + tx + "' menu item";
        var id = chrome.contextMenus.create({"title": title, "contexts":["selection"],
                                           "onclick": sendSearch(tx)});
        console.log("selection item:" + id);
    });
    

    Also note that "contexts":[selection] needs to be "contexts":["selection"], and "onclick": sendSearch(tx) needs to be something like this instead:

    "onclick": function(info, tab) {
        sendSearch(info.selectionText);
    }
    
    0 讨论(0)
提交回复
热议问题