在chrome扩展程序中,我试图基本上使用background.js作为API。这就是我的意思...
根据我对chrome扩展的理解,最终用户无权访问后台脚本。因此,在后台脚本中使用API密钥是安全的。 (如果这是错误的,请纠正我)。
目前,我的扩展程序看起来像这样: Application Workflow
例如:
Content.js函数-> background.js侦听器->外部api
Content.js回调<-background.js侦听器<-外部api
发生问题的原因是,通过chrome扩展名传递的消息具有两个选项。
chrome.runtime.sendMessage
进行“简单的一次性请求”
Unchecked runtime.lastError: The message port closed before a response was received.
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的响应。