javascript - onPageChanged 条件未加载
问题描述
我正在特定网站上构建一个 chrome 扩展,它应该显示弹出窗口。
网站列表超过 1000 个,我不能一个一个地写条件,这就是为什么我通过 GET 请求获取数据并解析它并以此为基础创建条件的原因。
function conditions() {
var conditionList = []
var request = new XMLHttpRequest();
request.open('GET', 'https://raw.githubusercontent.com/vaibhavmule/ycinfo/master/ycstartup.json', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var ycStartups = JSON.parse(request.responseText);
Object.keys(ycStartups).forEach(function (key) {
conditionList.push(
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlMatches: key + '\\..*' }
})
)
})
}
};
request.send();
return conditionList;
}
chrome.runtime.onInstalled.addListener(function(details) {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([
{
conditions: conditions(),
actions: [ new chrome.declarativeContent.ShowPageAction()]
}
]);
});
});
这是 Github 代码的链接:https ://github.com/vaibhavmule/ycinfo/blob/master/background.js
解决方案
您需要等到所有 yc 启动都被获取,然后调用addRules
函数。我在这里采取的方法是使用承诺,这样做。
function conditions() {
return fetch(`https://raw.githubusercontent.com/vaibhavmule/ycinfo/master/ycstartup.json`)
.then(function(res) {
if (res.status === 200) {
return res.json();
}
})
.then(function(ycStartups) {
console.log(ycStartups);
return Object.keys(ycStartups).map(function (key) {
return new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlMatches: key + '\\..*a' }
})
});
})
}
chrome.runtime.onInstalled.addListener(function(details) {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
conditions().then(function(res) {
chrome.declarativeContent.onPageChanged.addRules([
{
conditions: res,
actions: [ new chrome.declarativeContent.ShowPageAction()]
}
]);
});
});
});
推荐阅读
- excel - 根据多列条件复制部分行并根据相同条件粘贴到行
- javascript - 我可以检查一个函数绑定到什么吗?
- oracle - 合并 MERGE 和 INSERT ALL 语句
- api - 角度 6 中的 HTTP GET 401 授权要求错误
- javascript - 无法在 vue/webpack 中的绝对路径文件位置解析“products.json”
- linux - 如何等待变量的值设置为真,直到某个时间间隔
- sql-server - 如何从特定日期获取 3 个月之前的日期,比如 SQL 中的当前日期?
- mysql - 如何更新 AWS RDS MySQL 实例中的 --thread_stack 值?
- odoo - 来自 SQL 表的 Odoo 采购成本
- jenkins - 指向 Git 存储库作为 Jenkins Job DSL 作业的来源?