gpt4 book ai didi

javascript - 遍历选项卡以搜索字符串

转载 作者:行者123 更新时间:2023-11-28 02:41:29 24 4
gpt4 key购买 nike

我正在为 Chrome 扩展开发一个功能,我需要一些调试方面的帮助。

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

背景.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;
}

弹出脚本.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);
});
});

弹出窗口

<!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>

最佳答案

使用 chrome.tabs.executeScript我们可以检索标签的 innerText

background.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);
});
}

popup.js

...

var pagesFound = backgroundPage
.searchEverywhere(String(searchString.value), backgroundPage.makeAlert);

...

为简单起见,我使用了 setTimeout,但这并不是等待所有回调完成的最佳方式。我建议使用 promise 。

关于javascript - 遍历选项卡以搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44101182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com