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

Age*_*er1 3 html javascript google-chrome-extension

我在使用 chrome 扩展时遇到问题,。我有“标签”权限,但我不知道如何在没有背景页面的情况下检索页面上的选定文本。<---- 我改变主意了,我可以拥有背景页面。

这是脚本:

var code = document.getSelection().toString();
document.getElementsById("q").value = 代码;

我已经放置了一个chrome.executeCommand方法(不记得该方法是如何定向的),但这也不起作用。我不想要一个背景页面来防止安装此扩展程序时出现延迟。当我有背景时,它可能不会有太多延迟,但每一件都很重要。此外,基本上我的扩展将是关于便携式 Google It!扩展名,如果您突出显示/选择文本,它将自动设置输入字段的值。点击 https://www.dropbox.com/sh/c7q2puadva2vojf/GsuwWcXHjr查看我目前的进度!

gka*_*pak 5

(在几种可能的方法中)你可以像这样实现你想要的:

  1. 当您的弹出窗口加载时,用于chrome.tabs.executeScript()将一些代码注入选项卡的网页。
  2. 从注入的代码中查找并返回选定的文本。
  3. 使用返回的文本填充“搜索查询”输入字段。
  4. 单击“搜索”按钮后,打开一个包含 google 搜索结果的新标签。

以下是执行此操作的示例扩展的源代码:

maifest.json 中

{
    "manifest_version": 2,

    "name":    "Test Extension",
    "version": "0.0",

    "browser_action": {
        "default_title": "Test Extension",
        "default_popup": "popup.html"
    },

    "permissions": [
        "<all_urls>"
    ],
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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();
        }
    });
});
Run Code Online (Sandbox Code Playgroud)