代码之家  ›  专栏  ›  技术社区  ›  Vaibhav Mule

未加载onPageChanged条件

  •  1
  • Vaibhav Mule  · 技术社区  · 7 年前

    我正在一个特定的网站上建立一个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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Pankaj Thakur    7 年前

    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()]
            }
          ]);
        });
    
      });
    });
    

    这是我的公关: https://github.com/vaibhavmule/ycinfo/pull/3