10

我花了几个小时在网上搜索解决方案。我想做的是获取页面上突出显示的文本并将其传输到 chrome 扩展的 popup.html 中的文本区域。我想知道是否有人可以向我提供可以执行此操作的扩展的建议源代码。

这是我看过的最相关的线程,我认为最有帮助 - 查询是相似的。弹出窗口中获取选定文本的按钮 - Chrome 扩展

我尝试复制代码并将其作为扩展程序运行,它没有获得突出显示的文本。想知道是否有人有任何建议以及如何解决这个问题。非常感谢你。

4

3 回答 3

20

  就像您链接的问题的答案一样,您将需要使用Message PassingContent Scripts。不过,该代码已有 2 年多的历史了,并且使用了折旧的方法,例如onRequestgetSelected. 一些简单的修改应该足以将其更新为新的 api。

弹出窗口.html

<!DOCTYPE html> 
<html>
  <head>
    <script src="jquery-1.8.3.min.js"></script>
    <script src="popup.js"></script>
    <style>
      body { width: 300px; }
      textarea { width: 250px; height: 100px;}
    </style>
  </head>
  <body>
    <textarea id="text"> </textarea>
    <button id="paste">Paste Selection</button>
  </body>
</html>

popup.js(以免有任何内联代码)

$(function(){
  $('#paste').click(function(){pasteSelection();});
});
function pasteSelection() {
  chrome.tabs.query({active:true, windowId: chrome.windows.WINDOW_ID_CURRENT}, 
  function(tab) {
    chrome.tabs.sendMessage(tab[0].id, {method: "getSelection"}, 
    function(response){
      var text = document.getElementById('text'); 
      text.innerHTML = response.data;
    });
  });
}

选择.js

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

清单.json

{
 "name": "Selected Text",
 "version": "0.1",
 "description": "Selected Text",
 "manifest_version": 2,
 "browser_action": {
   "default_title": "Selected Text",
   "default_icon": "online.png",
   "default_popup": "popup.html" 
 },
 "permissions": [
   "tabs",
   "<all_urls>"
 ],
 "content_scripts": [
   {
     "matches": ["<all_urls>"],
     "js": ["selection.js"],
     "run_at": "document_start",
     "all_frames": true
   }
 ]
}

是源文件的链接。

于 2013-01-16T04:37:51.343 回答
7

popup.js

chrome.tabs.executeScript( {
  code: "window.getSelection().toString();"
}, function(selection) {
  alert(selection[0]);
});

清单.json

"permissions": [
    "activeTab",
],

看看这个简单的扩展https://github.com/kelly-apollo/zdic

于 2016-06-16T03:14:28.197 回答
0

参考下面的 BeardFist 答案

此外,在 popup.html 中,您可以使用 CDN 版本:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

并在清单文件中添加这一行:

 "content_security_policy": "script-src 'self' 'unsafe-eval' https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js; object-src 'self'",
于 2021-12-18T20:46:24.453 回答