迭代选项卡以搜索字符串

时间:2017-05-21 19:54:50

标签: javascript jquery html google-chrome-extension

我正在开发Chrome扩展程序的功能,我需要一些帮助调试。

该函数应该从popup.html文本框中获取用户的String输入,并查看当前窗口中的所有选项卡,以查看String输入是否存在于任何选项卡中。最后,我发出警告,告诉用户在哪个标签(索引:0,1,...)中找到了字符串。

background.js

//searches all tabs for the input string
function searchEverywhere(searchString) {
    var indices = [];
    chrome.tabs.query({}, function(tabs) {
        var numOfTabs = tabs.length;
        for(i = 0; i < numOfTabs; i++) {
            chrome.tabs.update(tabs[i].id, updateProperties, function(tab) {
                if(getText().indexOf(searchString) > -1) {
                    indices.push(i);
                }
            }); 
        }
    });
    return indices;
}
function makeAlert(pagesFound) {
    alert("Your input was found on tabs: " + pagesFound.toString());
}
function getText() {
    return document.body.innerText;
}

popup_script.js

document.addEventListener("DOMContentLoaded", function() {
    var backgroundPage = chrome.extension.getBackgroundPage();

    document.querySelector('#btnSearch').addEventListener('click', function() {
        var searchString = document.querySelector('#textToSearch');
        var pagesFound = backgroundPage.searchEverywhere(String(searchString.value));
        backgroundPage.makeAlert(pagesFound);
    });
});

popup.html

<!DOCTYPE html>
<html>
    <head>
        <title>Work with tabs</title>
        <script src="popup_script.js"></script>
    </head>
    <body><div class="searchEverywhere">
        Search all tabs for word:<br>
            <input type="text" name="textToSearch" id="textToSearch">
            <br>
            <input type="button" id="btnSearch" value="Search">
        </div>

    </body>
</html>

1 个答案:

答案 0 :(得分:0)

使用chrome.tabs.executeScript,我们可以检索标签的SELECT * FROM PIZZACONDIMENT WHERE CONDIMENT = 'Spinach'; CONDIMENT PIZZASIZE PIZZAPRICE Spinach 50 7.5

<强> background.js

innerText

<强> popup.js

function searchEverywhere(searchPhrase, callback) {
    chrome.tabs.query({
        //query only tabs that you have enabled permissions for or you will get errors in console
    }, tabs => {
        let foundInTabIds = [];

        for (let tab of tabs) {
            chrome.tabs.executeScript(tab.id, {
                code: `document.body.innerText`
            }, (results => {
                if (results && results.length > 0) {
                    let tabText = results[0];
                    if(tabText.indexOf(searchPhrase) > -1) {
                        foundInTabIds.push(tab.id);
                    }
                }
            }));
        }

        setTimeout(() => {
            //your alert
            callback(foundInTabIds);
        }, 2000);
    });
}

为简单起见,我使用... var pagesFound = backgroundPage .searchEverywhere(String(searchString.value), backgroundPage.makeAlert); ... ,但这不是等待所有回调完成的最佳方式。我建议使用promises。