Javascript 从chrome扩展中的上下文菜单获取所选文本的html源

Javascript 从chrome扩展中的上下文菜单获取所选文本的html源,javascript,google-chrome,google-chrome-extension,selection,Javascript,Google Chrome,Google Chrome Extension,Selection,我试图通过点击google chrome扩展中的上下文操作(获取突出显示的文本本身不是我想要的)来获取所选文本的html源 以下背景脚本(coffee源代码)尝试通过executeScript和sendRequest访问选择对象(作为中间步骤)。但是,选择和响应是 未定义。为什么失败?正确的方法是什么 logSelectionViaExecuteScript= -> chrome.tabs.executeScript code: "window.getSelection().t

我试图通过点击google chrome扩展中的上下文操作(获取突出显示的文本本身不是我想要的)来获取所选文本的html源

以下背景脚本(coffee源代码)尝试通过
executeScript
sendRequest
访问选择对象(作为中间步骤)。但是,
选择
响应
是 未定义。为什么失败?正确的方法是什么

logSelectionViaExecuteScript= ->
  chrome.tabs.executeScript
    code: "window.getSelection().toString();" , (selection) ->
      console.log 
        name: 'logSelectionViaExecuteScript'
        selection: selection

logSelectionViaSendRequestThroughTabs= (tabId)->
  chrome.tabs.sendRequest tabId, {method: "getSelection"}, (response)->
    console.log 
      name: 'logSelectionViaSendRequestThroughTabs'
      tabId: tabId
      response: response

onClickAction= (info, tab)->
  console.log  info: info
  console.log  tab: tab 
  logSelectionViaSendRequestThroughTabs(tab.id)
  logSelectionViaExecuteScript()

chrome.contextMenus.create
  title:"Highlight '%s'"
  contexts: ["selection"]
  onclick: onClickAction
我知道有些函数已被弃用。但是,根据我对文档的理解,它们仍然可以工作

编辑:


问题解决后,Github上的示例已被删除

我误解了API的描述。以下是它的工作原理:

在后台脚本中:

logSelectionViaSendMessageThroughTabs= (tabId)->
  chrome.tabs.sendMessage  tabId, {method: "getSelection"}, (response)->
    console.log 
      name: 'logSelectionViaSendMessageThroughTabs'
      tabId: tabId
      response: response
注意使用了
sendMessage
,这是一个不推荐使用的函数

以下是内容脚本的片段:

chrome.runtime.onMessage.addListener (message,sender,sendResponse)->
  if message.method is "getSelection" 
    selection= window.getSelection()
    # do something with selection and send it off with sendResponse

所选文本的html源是什么意思?如果所选文本包含一些修改html标记,您是在查找修改html标记,如,,还是在查找完全包含所选文本的最内部html元素?最后,我想修改dom中与所选文本相对应的元素。我还想“记住”所选的html。请发布足够的代码,以便潜在的回答者重现您的环境。例如,manifest.json和后台页面的其余部分(如果有)。用JavaScript编写代码也会很有帮助,这样其他人就可以运行代码,而无需使用CoffeeScript翻译程序。请参阅说明中的编辑。如果没有任何内容侦听它,您甚至希望从
sendRequest
中得到什么?