2016-11-22 74 views
3

我正在尋找一種將我的選定文本添加到我的Chrome擴展中的框架/邊框(如Evernote Web Clipper:下圖)。Chrome擴展選定的文本

enter image description here

爲了做到這一點,我想捕捉選擇的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]; 
     } 
}); 

彈出.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> 
+0

popup.html中文本區域的用法是什麼? – sabithpocker

+0

@sabithpocker這只是一個臨時預覽。 – Steve23

回答

2

您可以使用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

    但現實生活中,應該是比較複雜的,想到的棘手的

  • 選擇內部的圖像
  • 上有很多不同的情況

除去亮點也許它可以是一個好主意,不斷查詢DOM的選擇對象與window.requestAnimationFrame()而不是添加事件偵聽器mouseup