Pass Variable To Badge Text In Chrome Extension
I have built an extension that grabs some info from a div on a page and stores it in a variable called 'div'. I now need to pass that value into my background.js file so that I ca
Solution 1:
You need Messaging.
The documentation is good on this topic; however, a short overview:
Extension page can register a listener for a
chrome.runtime.onMessage
event.The content script calls
chrome.runtime.sendMessage
to broadcast a JSON-serializable message to all extension pages in its parent extension.
See this architecture overview for a better definition of "extension page"
I expressly emphasized "JSON-serializable", because an HTMLElement
is not serializable. You need to extract the properties you need (like innerText
) before sending.
// Background script
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
// It is recommended to add a message type so your code// can be ready for more types of messages in the futureswitch(message.type) {
case"updateBadge":
// Do stuff with message.databreak;
default:
console.warn("Unrecognized message type: " + message.type);
break;
}
});
// Content scriptvar div = document.getElementById("sessions_queued_now_row-000");
var data = { text : div.innerText /*, something else?*/ };
chrome.runtime.sendMessage({ type: "updateBadge", data: data });
Post a Comment for "Pass Variable To Badge Text In Chrome Extension"