javascript - onPageChanged 条件未加载

标签 javascript google-chrome-extension

我正在特定网站上构建一个 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 函数。我在这里采用的方法是使用 promise ,这样做。

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

关于javascript - onPageChanged 条件未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52960215/

相关文章:

javascript - 如何根据用户选择顺序重新排序多重选择的值

google-chrome - 如何从任何页面的 javascript 访问 google chrome 扩展

google-chrome-extension - Chrome 扩展程序可以与 USB 设备通信吗?

javascript - 内容脚本未显示在 Chrome 开发工具中

javascript - 如何将从客户端浏览器抓取的数据保存到用户文件中?使用 Electron ?

javascript - 是否可以捕获内部创建的 bing map 实体的事件?

Javascript:返回对象内数组的第一个值

javascript - 如何使用正则表达式验证我的文件输入名称?

javascript - 如何解决Bootstrap中的 "style sheet could not be loaded"

javascript - chrome 扩展 `sendResponse` 不起作用