[英]Chrome Extension get selected text
I am looking for a way to get the selected text into my Chrome extension.我正在寻找一种将所选文本放入我的 Chrome 扩展程序的方法。
I want to ex.我想前任。 select a text in facebook feed and when I click my icon it will get it and show the selected text in my Extension.
在 facebook feed 中选择一个文本,当我点击我的图标时,它会得到它并在我的扩展中显示选定的文本。
I got this so far:到目前为止我得到了这个:
chrome.tabs.executeScript(null, {
code: "alert(window.getSelection().toString());"
})
it gets the selected text and alert it with a message in Chrome.它获取选定的文本并在 Chrome 中用消息提醒它。 However I want to show it in my html popup.
但是我想在我的 html 弹出窗口中显示它。 I want to write it out like this:
我想这样写:
document.getElementById("output").value = "Selected text here(but how)"
Need help!需要帮助! and I know there is other question about this, but they didn't give me exactly what I want..
我知道还有其他问题,但他们没有给我我想要的。
You can use the last expression evaluated by the executed code in a callback function:您可以在回调函数中使用由执行的代码计算的最后一个表达式:
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
document.getElementById("output").value = selection[0];
});
You can do this by using Extensions Messaging .您可以通过使用Extensions Messaging来做到这一点。 Basically, your "background page" will send the request to your service.
基本上,您的“背景页面”会将请求发送到您的服务。 For example, lets say you have a "popup" and once you click on it, it will do a "Google search" which is your service.
例如,假设您有一个“弹出窗口”,一旦您点击它,它就会进行“Google 搜索”,这是您的服务。
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
Some References一些参考资料
Or you can use this plugin或者你可以使用这个插件
For Angular 8.2 I use this code:对于 Angular 8.2,我使用以下代码:
chrome.tabs.executeScript( { code: 'window.getSelection().toString();'}, selectedText => {
(document.getElementById('text-input') as HTMLInputElement).value = selectedText[0];
console.log(selectedText[0]);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.