繁体   English   中英

Chrome扩展程序已选定文字

[英]Chrome Extension selected text

我正在寻找一种方法,将我所选文本周围的框架/边框(如Evernote Web Clipper:下图)添加到我的Chrome扩展程序中。

在此输入图像描述

为此,我想捕获选择的HTML代码并在当前所选文本周围添加框架/边框。 但我不知道我怎么能这样做......

这是我的代码:

manifest.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": ["popup.js"]
   }
 ]
}

popup.js:

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

      console.log(selection[0]);
      if(selection[0].length > 0){
        document.getElementById("text").value = selection[0];
      }
});

popup.html:

<!DOCTYPE html> 
<html>
  <head>
    <script src="popup.js"></script>
    <style>
      body { width: 300px; }
      textarea { width: 250px; height: 100px;}
    </style>
  </head>
  <body>
    <textarea id="text"> </textarea>
  </body>
</html>

你可以使用像这样的mouseup事件:

 // Add event listener for mouseup (there is no event for selection) document.addEventListener('mouseup', highlightSelectedBlock, false) function highlightSelectedBlock () { // TODO Filter only selections // Get Node where selection starts let elementWhereSelectionStart = window.getSelection().anchorNode // TODO Get Node where selection ends with Selection.focusNode() // TODO Get Nodes in between start and end of selection // I've hardcoded finding closest block element for a simplicity let closestBlockElement = elementWhereSelectionStart.parentNode // Add non disturbing border to selected elements // For simplicity I've adding outline only for the start element closestBlockElement.style.outline = '1px solid blue' // TODO Clear outline on some event: saving selection, ending selection etc setTimeout(() => { closestBlockElement.style.outline = 'none' }, 2000) } 
 <p>First line <p>Second line <p>Third line 

但对于现实生活来说,它应该更复杂,想一想:

  • 键盘选择
  • 突出几个元素,这可能很棘手
  • 选择里面的图像
  • 删除许多不同情况下的突出显示

也许用window.requestAnimationFrame()不断地为选择对象轮询DOM是一个好主意,而不是向mouseup添加事件监听器。

暂无
暂无

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

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