Chrome扩展程序:使用Background从API获取数据

时间:2019-11-18 15:12:31

标签: google-chrome-extension

我的内容中有

test = await chrome.runtime.sendMessage({ title: "getMyData" }, (res) => {
    console.log({res});
});
console.log({test});

背景:

    chrome.runtime.onMessage.addListener( (request, sender, sendResponse) => {
        if (request.hasOwnProperty("title")) {
            switch (request.title) {
                case "getMyData": {
                    sendResponse({test:"test value"});
                    return true;
                }
            }         
        } 
    }

我要发送内容消息并通过fetch()获取一些数据。

有了这些代码,我只会变得不确定。

1 个答案:

答案 0 :(得分:0)

我们可以通过两种方式做到这一点:

方法1 :在后台情况“ getMyData”中,调用一个单独的函数以获取API数据,然后尝试返回“ chrome.runtime.sendMessage ”内容脚本以使用相同的“ chrome.runtime.onMessage.addListener ”方法接收响应。这将是一种更清洁和模块化的方式。

方法2 :直接在“ chrome.runtime.onMessage.addListener ”中调用 fetch(),获取响应并进行更新它返回到如下内容脚本:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.hasOwnProperty("title")) {
    switch (request.title) {
      case "getMyData": {
        var url = request.url; //Your API endpoint
        fetch(url)
          .then(response => response.text())
          .then(response => sendResponse(response))
          .catch()
        return true;
      }
    }
  }
}
相关问题