Chrome扩展程序获取所选文字

Chr*_*sen 25 html javascript google-chrome google-chrome-extension

我正在寻找一种方法将所选文本添加到我的Chrome扩展程序中.

我想要前.在Facebook Feed中选择一个文本,当我点击我的图标时,它将获取它并在我的扩展程序中显示所选文本.

我到目前为止得到了这个:

chrome.tabs.executeScript(null, {
  code: "alert(window.getSelection().toString());"
})
Run Code Online (Sandbox Code Playgroud)

它会获取所选文本并通过Chrome中的消息提醒它.但是我想在我的html弹出窗口中显示它.我想写出来像这样:

document.getElementById("output").value = "Selected text here(but how)"
Run Code Online (Sandbox Code Playgroud)

需要帮忙!而且我知道还有其他问题,但他们没有给我我想要的东西..

rsa*_*hez 35

您可以在回调函数中使用由执行代码计算的最后一个表达式:

chrome.tabs.executeScript( {
  code: "window.getSelection().toString();"
}, function(selection) {
  document.getElementById("output").value = selection[0];
});
Run Code Online (Sandbox Code Playgroud)


Vai*_*ool 8

您可以使用Extensions Messaging来完成此操作。基本上,您的“后台页面”会将请求发送到您的服务。例如,假设您有一个“弹出窗口”,一旦您单击它,它将执行“Google 搜索”,这是您的服务。

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.method == "getSelection")
      sendResponse({data: window.getSelection().toString()});
    else
      sendResponse({}); // snub them.
});
Run Code Online (Sandbox Code Playgroud)

一些参考资料

  1. 创建一个 chrome 扩展,它获取页面上突出显示的文本并将其插入到 popup.html 中的文本区域中

或者你可以使用这个插件

  1. https://chrome.google.com/webstore/detail/view-selection-source/fbhgckgfljgjkkfngcoeajbgndkeoaaj