首页 > 解决方案 > 使用键盘快捷键运行 chrome 扩展

问题描述

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

谢谢

标签: javascriptgoogle-chrome-extension

解决方案


推荐阅读