In a chrome extension I'm trying to basically use the background.js as an API. Here's what I mean...
From my understanding of chrome extensions, the end-user does not have access to the background scripts. For this reason it is safe to use API keys inside a background script. (If this is wrong please someone correct me).
Currently my extension looks a little something like this: Application Workflow
Ex:
Content.js function -> background.js listener -> external api
Content.js callback <- background.js listener <- external api
The issue occurs in that the message passing for chrome extensions have two options.
- "Simple one-time requests" via
chrome.runtime.sendMessage
- Limitation:
Unchecked runtime.lastError: The message port closed before a response was received.
- Limitation:
- "Long-lived connections" via
port.postMessage
.- Limitation: No callback function
Research
Attempts
With method 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
});
})
});
Result
Error: Unchecked runtime.lastError: The message port closed before a response was received.
the callback is called and logs unndefined
With method 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
});
});
});
});
Result
The callback function is lost as postMessage
accepts only json, so functions are stripped
I think the best course of action will have something to do with method 1 and promises but I'm just not sure how to make it work correctly. At the end of the day the content script needs to get the api's response in a callback function.