简体   繁体   English

弹出窗口中获取所选文本的按钮-Chrome扩展程序

[英]Button in popup that get selected text - Chrome extension

In my popup.html in my chrome extension I have a button that will get the selected text in de webpage and put it in my textarea in the popup.html. 在我的chrome扩展程序的popup.html中,我有一个按钮,它将在网页中获取选定的文本并将其放在popup.html中的textarea中。

  1. First I select text in a webpage 首先,我在网页中选择文本
  2. I click on my extension. 我点击我的扩展程序。 An popup will show with a textarea and a button. 将显示一个弹出窗口,其中包含文本区域和按钮。
  3. When I Push the button the selected text will show in my textarea. 当我按下按钮时,所选文本将显示在我的文本区域中。

is someone who can help me with this issue, 是可以帮助我解决这个问题的人,

Thanks, 谢谢,

Wouter 伍特

If you want to implement that, you would need to use a couple of API's. 如果要实现这一点,则需要使用几个API。

You need to make sure of Content Scripts in order to capture selection within the DOM. 您需要确保内容脚本才能捕获DOM中的选择。 Then you need to use Message Passing to let the Popup communicate to the Content Script. 然后,您需要使用消息传递来使弹出窗口与内容脚本进行通信。 After you do all that, you can simply use chrome.tabs.sendRequest to send a message to the Content Script so that you get back a response with the data. 完成所有这些操作后,您可以简单地使用chrome.tabs.sendRequest将消息发送到内容脚本,以便您获取数据的响应。

For example, this is how you can do a Popup that fetches the current selection: 例如,这是您可以执行以下操作来获取当前选择的方法:

popup.html popup.html

<!DOCTYPE html> 
<html>
<head>
<style>
  body { width: 300px; }
  textarea { width: 250px; height: 100px;}
</style>
<script>
function pasteSelection() {
  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function (response) {
      var text = document.getElementById('text'); 
      text.innerHTML = response.data;
    });
  });
}
</script>
</head>
<body>
<textarea id="text"> </textarea>
<button onclick="pasteSelection(); ">Paste Selection</button>
</body>
</html>

selection.js selection.js

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

manifest.json manifest.json

{
 "name": "Selected Text",
 "version": "0.1",
 "description": "Selected Text",
 "browser_action": {
   "default_title": "Selected Text",
   "default_icon": "online.png",
   "default_popup": "popup.html" 
 },
 "permissions": [
   "tabs",
   "chrome://favicon/",
   "http://*/*", 
   "https://*/*"
 ],
 "content_scripts": [
  {
    "matches": ["http://*/*"],
    "js": ["selection.js"],
    "run_at": "document_start",
    "all_frames": true
  }
 ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM