Я создаю расширение 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
Вам нужно подождать до тех пор, addRules
весь запуск 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()]
}
]);
});
});
});
вот мой PR: https://github.com/vaibhavmule/ycinfo/pull/3