Javascript Chrome扩展获取所选文本
我正在寻找一种方法,以获得我的铬扩展选定的文本 我想在facebook feed中选择一个文本,当我点击我的图标时,它会得到它并在我的分机中显示所选文本 到目前为止,我已经做到了:Javascript Chrome扩展获取所选文本,javascript,html,google-chrome,google-chrome-extension,Javascript,Html,Google Chrome,Google Chrome Extension,我正在寻找一种方法,以获得我的铬扩展选定的文本 我想在facebook feed中选择一个文本,当我点击我的图标时,它会得到它并在我的分机中显示所选文本 到目前为止,我已经做到了: chrome.tabs.executeScript(null, { code: "alert(window.getSelection().toString());" }) 它获取所选文本,并在Chrome中显示一条消息提醒它。但是我想在我的html弹出窗口中显示它。我想这样写出来: document.getEl
chrome.tabs.executeScript(null, {
code: "alert(window.getSelection().toString());"
})
它获取所选文本,并在Chrome中显示一条消息提醒它。但是我想在我的html弹出窗口中显示它。我想这样写出来:
document.getElementById("output").value = "Selected text here(but how)"
需要帮助!我知道还有其他问题,但他们没有给我想要的 您可以使用。基本上,您的“背景页面”将向您的服务发送请求。例如,假设您有一个“弹出窗口”,一旦您单击它,它将执行“谷歌搜索”,这是您的服务
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
一些参考资料
或者你可以使用这个插件
您可以在回调函数中使用执行代码计算的最后一个表达式:
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
document.getElementById("output").value = selection[0];
});
对于Angular 8.2,我使用以下代码:
chrome.tabs.executeScript( { code: 'window.getSelection().toString();'}, selectedText => {
(document.getElementById('text-input') as HTMLInputElement).value = selectedText[0];
console.log(selectedText[0]);
});
这不会将其发送到我的html文档?未捕获错误:extension.sendRequest、extension.onRequest和extension.onRequestExternal不推荐使用。请改用runtime.sendMessage、runtime.onMessage和runtime.onMessageExternal。这是我最后得到的结果:chrome.tabs.executeScript(null,{code:“window.getSelection().toString();”),函数(results){document.getElementById(“output”).value=results;}工作!它在相同的原始帧和不同的原始帧中不工作。它还经常返回未实际选择的文本,因为焦点现在在不同的帧中。它在输入字段中也不工作,但这不是问题:
code let el=activeWindow.document.activeElement;if(isTextElem(el)){if(&el.selectionStart!==el.selectionEnd中的“selectionStart”{返回el.value.substring(el.selectionStart,el.selectionEnd);}}