[英]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.