I’m trying to communicate from content.js to background.js to save some data to the chrome.storage.local but I can’t figure out how to do it correctly.
I’m not very familiar with js so forgive me if it’s a stupid question.
That’s the code:
content.js
function sendMessage(type) {
chrome.runtime.sendMessage({ action: type }, (response) => {
console.log(response);
});
}
sendMessage("test");
background.js
// Listen for messages from content scripts
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "test") {
saveData(sendResponse);
}
return true;
});
// Function to save data to Chrome local storage
function saveData(sendResponse) {
// Sample data to save
const test = ["test1", "test2", "test3"];
chrome.storage.local.set({ test: test }, () => {
sendResponse("saved");
});
}
result:
undefined
Unchecked runtime.lastError: The message port closed before a response was received.
What I’m doing wrong?