【问题标题】:Chrome Extension get selected textChrome 扩展获取选定的文本
【发布时间】:2013-10-10 11:07:05
【问题描述】:

我正在寻找一种将所选文本放入我的 Chrome 扩展程序的方法。

我想前任。在 facebook feed 中选择一个文本,当我点击我的图标时,它会得到它并在我的扩展中显示选定的文本。

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

chrome.tabs.executeScript(null, {
  code: "alert(window.getSelection().toString());"
})

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

document.getElementById("output").value = "Selected text here(but how)"

需要帮助!我知道对此还有其他问题,但他们并没有给我我想要的东西..

【问题讨论】:

  • 这就是我最终得到的结果: chrome.tabs.executeScript( null, {code:"window.getSelection().toString();"}, function(results){ document.getElementById( "输出").value = 结果;} 有效!

标签: javascript html google-chrome google-chrome-extension


【解决方案1】:

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

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

【讨论】:

  • 同源帧和异源帧都不起作用。它还经常返回实际上未选择的文本,因为现在焦点在不同的框架中。它在输入字段中也不起作用,但这不是问题:code let el = activeWindow.document.activeElement; if (isTextElem(el)) { if ('selectionStart' in el && el.selectionStart !== el.selectionEnd) { return el.value.substring(el.selectionStart, el.selectionEnd); } }
【解决方案2】:

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

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

一些参考资料

  1. Creating a chrome extension which takes highlighted text on the page and inserts it into a textarea in popup.html

或者你可以使用这个插件

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

【讨论】:

  • 这不会发送到我的 html 文档?
  • 未捕获的错误:extension.sendRequest、extension.onRequest 和 extension.onRequestExternal 已弃用。请改用 runtime.sendMessage、runtime.onMessage 和 runtime.onMessageExternal。
【解决方案3】:

对于 Angular 8.2,我使用以下代码:

chrome.tabs.executeScript( { code: 'window.getSelection().toString();'}, selectedText => {
 (document.getElementById('text-input') as HTMLInputElement).value = selectedText[0];
  console.log(selectedText[0]);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2016-03-14
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    相关资源
    最近更新 更多