Chrome Extension Highlighted Text selection chrome.tabs

前端 未结 1 1616
不知归路
不知归路 2021-01-14 03:36

I\'m having trouble with chrome extensions,. I have the permission \"tabs\" but I don\'t know how to retrieve the selected text on the page WITHOUT< a background page. &l

相关标签:
1条回答
  • 2021-01-14 04:28

    (Among several possible approaches) you can achieve what you want like this:

    1. When your popup is loaded, use chrome.tabs.executeScript() to inject some code into the tab's web-page.
    2. From the injected code find and return the selected text.
    3. Populate the "search-query" input field with the returned text.
    4. when the "search" button is clicked, open a new tab with the google search results.

    Below is the source code of a sample extension that does exactly that:

    In maifest.json:

    {
        "manifest_version": 2,
    
        "name":    "Test Extension",
        "version": "0.0",
    
        "browser_action": {
            "default_title": "Test Extension",
            "default_popup": "popup.html"
        },
    
        "permissions": [
            "<all_urls>"
        ],
    }
    

    In popup.html:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Google It!</title>
            <script type="text/javascript" src="popup.js"></script>
        </head>
        <body>
            <input type="text" id="inp" size="20" placeholder="Search query..." />
            <br />
            <input type="button" id="btn" value="Google It!" />
        </body>
    </html>
    

    In popup.js:

    /* The URL for the Google search */
    var google = 'http://google.com/#q=';
    
    /* The function that finds and returns the selected text */
    var funcToInject = function() {
        var range = window.getSelection().getRangeAt(0);
        var selectedText = range.cloneContents().textContent;
        return selectedText;
    };
    /* This line converts the above function to string
     * (and makes sure it will be called instantly) */
    var jsCodeStr = ';(' + funcToInject + ')();';
    
    window.addEventListener('DOMContentLoaded', function() {
    
        /* Find our input elements from `popup.html` */
        var inp = document.querySelector('input[type="text"]#inp');
        var btn = document.querySelector('input[type="button"]#btn');
    
        /* Open a new tab with the search results */
        btn.addEventListener('click', function() {
            var query = encodeURIComponent(inp.value);
            chrome.tabs.create({ url: google + query });
        });
    
        /* Inject the code into all frames of the active tab */
        chrome.tabs.executeScript({
            code: jsCodeStr,
            allFrames: true
        }, function(selectedTextPerFrame) {
    
            if (chrome.runtime.lastError) {
                /* Report any error */
                alert('ERROR:\n' + chrome.runtime.lastError.message);
            } else if ((selectedTextPerFrame.length > 0)
                    && (typeof(selectedTextPerFrame[0]) === 'string')) {
                /* The results are as expected, 
                 * populate the "search-query" input field */
                inp.value = selectedTextPerFrame[0].trim();
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题