Javascript 将变量传递到Chrome扩展中的徽章文本
我构建了一个扩展,它从页面上的div中获取一些信息,并将其存储在一个名为“div”的变量中。我现在需要将该值传递到background.js文件中,以便更新徽章以反映该变量中的文本 我已经阅读了sendMessage信息,但每次我在页面中添加代码行时,它似乎会破坏扩展,因此我肯定是做错了什么 以下是代码,其中没有setBadgeText信息(当前正在运行) getQueue.jsJavascript 将变量传递到Chrome扩展中的徽章文本,javascript,jquery,google-chrome,google-chrome-extension,Javascript,Jquery,Google Chrome,Google Chrome Extension,我构建了一个扩展,它从页面上的div中获取一些信息,并将其存储在一个名为“div”的变量中。我现在需要将该值传递到background.js文件中,以便更新徽章以反映该变量中的文本 我已经阅读了sendMessage信息,但每次我在页面中添加代码行时,它似乎会破坏扩展,因此我肯定是做错了什么 以下是代码,其中没有setBadgeText信息(当前正在运行) getQueue.js var myVar = null; setFunction(); function setFunction() {
var myVar = null;
setFunction();
function setFunction() {
myVar = setInterval(function () {myTimer();}, 10000);
}
function myTimer() {
var THRESHOLD = 0;
var div = document.getElementById("sessions_queued_now_row-000");
var num = parseInt(div.innerText);
// Here is where I want to pass div to background.js to update the badge text
if (num >= THRESHOLD) {
// I do a bunch of stuff here
}
}
我的background.js文件现在做的不多,但在一个新选项卡中打开了一个URL
我正在寻找需要添加到getQueue.js文件和background.js文件中的内容
谢谢你所需要的
关于这个主题的文档很好;但是,简要概述如下:
chrome.runtime.onMessage
事件注册侦听器chrome.runtime.sendMessage
,向其父扩展中的所有扩展页广播一条JSON serializable消息HTMLElement
是不可序列化的。在发送之前,您需要提取所需的属性(如innerText
)
// 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 future
switch(message.type) {
case "updateBadge":
// Do stuff with message.data
break;
default:
console.warn("Unrecognized message type: " + message.type);
break;
}
});
// Content script
var div = document.getElementById("sessions_queued_now_row-000");
var data = { text : div.innerText /*, something else?*/ };
chrome.runtime.sendMessage({ type: "updateBadge", data: data });