Chrome getSelection not working if called from context menu

▼魔方 西西 提交于 2020-01-05 07:14:31

问题


I'm working on a Chrome extension but I don't seem to be able to go past the first few lines. The problem is that when I click on the context menu it fails to grab the selection from the document. It works fine obviously when I use it as a simple script included in an HTML page.

Here's the code:

var id = chrome.contextMenus.create({
    "title" : "Search",
    "contexts" : ["selection"],
    "onclick" : openUrl
});

function openUrl() {
    var sel = window.getSelection().toString().trim()
    alert(sel)
}

This code returns an empty alert box.

I have a script that on mouseup grabs the word that the user has selected and searches for this word on a dictionary. This script works fine I just need to execute it when the user clicks "Search" in the context menu. So what I'm looking for is: 1) User selects a word from the document 2) Right clicks on it and clicks on the context menu 3) The script containing all instruction to be executed on that click.

I looked around before asking this question but I couldn't find anything probably because I'm pretty new to this awesome site. Please feel free to redirect me to other similiar question if I missed any. Thanks!


回答1:


function openUrl(info, tab) {
     alert(info.selectionText);
}


来源:https://stackoverflow.com/questions/11222130/chrome-getselection-not-working-if-called-from-context-menu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!