使用键盘快捷键运行Chrome扩展程序

时间:2018-09-17 15:48:04

标签: javascript google-chrome-extension

我非常了解js,并且正在开发Google Chrome扩展程序。我的目的是创建一个扩展,以选择(突出显示)某些文本并打开一个弹出窗口,其中包含来自查询的结果。

此代码可以完美运行,但是,我需要打开扩展名并单击一个按钮来执行此操作。你能帮我吗?

这是js代码

/* 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.windows.create({ type: 'popup', height: 600, width:600, url: url + 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 个答案:

没有答案