gpt4 book ai didi

javascript - Chrome 扩展选择的文本

转载 作者:可可西里 更新时间:2023-11-01 13:24:36 26 4
gpt4 key购买 nike

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

enter image description here

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

这是我的代码:

list .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"]
}
]
}

弹出.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

关于javascript - Chrome 扩展选择的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746567/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com