How to get selected text in chrome extension development?

后端 未结 2 473
星月不相逢
星月不相逢 2021-01-05 20:45

I\'m developing a chrome extension which involves getting selected text of the current tab. Here is the html file that I use:




        
2条回答
  •  悲哀的现实
    2021-01-05 21:20

    As @Xan suggested, the method mentioned before (you can find it here) is overcomplicated. To get it to work, there are only two things to do:

    1. Change value to innerHTML in document.getElementById("output").value

    2. Add an activeTab permission in manifest.json file

    Here is the complete source code, three files in total.

    manifest.json

    {
        "manifest_version": 2,
        "name": "sample",
        "description": "A sample extension to get the selected text",
        "version": "1.0",
        "icons": { 
            "16": "img/icon16.png",
            "48": "img/icon48.png",
            "128": "img/icon128.png" 
        },
        "browser_action": {
            "default_popup": "popup.html"
        },
        "permissions": [
            "activeTab"
        ]
    }
    

    popup.html

    
    
        
            
            
            
        
        
            

    popup.js

    chrome.tabs.executeScript( {
        code: "window.getSelection().toString();"
    }, function(selection) {
        document.getElementById("output").innerHTML = selection[0];
    });
    

提交回复
热议问题