使用Chrome Extension Background.js作为API中间人

时间:2019-05-06 00:50:13

标签: javascript api google-chrome-extension promise sendmessage

在chrome扩展程序中,我试图基本上使用background.js作为API。这就是我的意思...

根据我对chrome扩展的理解,最终用户无权访问后台脚本。因此,在后台脚本中使用API​​密钥是安全的。 (如果这是错误的,请纠正我)。

目前,我的扩展程序看起来像这样: Application Workflow

例如:

Content.js函数-> background.js侦听器->外部api

Content.js回调<-background.js侦听器<-外部api

发生问题的原因是,通过chrome扩展名传递的消息具有两个选项。

  1. 通过chrome.runtime.sendMessage进行“简单的一次性请求”
    • 限制条件:Unchecked runtime.lastError: The message port closed before a response was received.
  2. 通过port.postMessage的“长期连接”。
    • 限制:没有回调函数

研究

尝试

  

使用方法1

content.js

chrome.runtime.sendMessage({action: "hello from content"}, response => {
  console.log("content: callback", response);
});

background.js

chrome.runtime.onMessage.addListener(async function(message, sender, sendResponse) {
    return new Promise((resolve, reject) => {
        GetCurrentlyPlaying()
            .then((response) => {
                    //sendResponse({response: response}); // tried using this
                    //resolve({response: response}); // also tried using this, also tried both
            });
    })
});

结果

错误:Unchecked runtime.lastError: The message port closed before a response was received.回调被调用并记录unndefined

  

使用方法2

content.js

let port = chrome.runtime.connect();

port.postMessage({
  callback: function(response) {
    console.log('content: callback', response);
  }
});

port.onMessage.addListener(function (message) {
  if (message.callback && message.data) {
    message.callback(message.data);
    return;
  }
});

background.js

chrome.runtime.onConnect.addListener(function (port) {
    port.onMessage.addListener(function (message) {
            GetCurrentlyPlaying()
                .then((response) => {
                    port.postMessage({
                        callback: message.callback,
                        data: response
                    });
                });
    });
});

结果

由于postMessage仅接受json,因此回调函数丢失,因此剥离了函数


我认为最好的行动方案与方法1有关,并且承诺了,但是我不确定如何使其正确工作。最终,内容脚本需要在回调函数中获取api的响应。

0 个答案:

没有答案