且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Chrome扩展程序突出显示文本选择chrome.tabs

更新时间:2023-12-05 18:38:10

(在几种可能的方法中)你可以达到你想要的效果:

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


  1. 加载弹出窗口后,使用 chrome.tabs.executeScript() 将一些代码注入选项卡的网页。

  2. 从注入的代码中查找并返回所选文本。

  3. 使用返回的文本填充搜索查询输入字段。

  4. 单击搜索按钮时,打开一个新选项卡,谷歌搜索结果。

  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:

maifest.json

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>"
    ],
}

popup.html

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>

popup.js

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();
        }
    });
});