ส่งตัวแปรไปยังข้อความตราสัญลักษณ์ในส่วนขยายของ Chrome

ฉันได้สร้างส่วนขยายที่ดึงข้อมูลบางส่วนจาก div บนเพจและจัดเก็บไว้ในตัวแปรที่เรียกว่า 'div' ตอนนี้ฉันต้องส่งค่านั้นไปยังไฟล์ background.js ของฉันเพื่อที่จะสามารถอัปเดตป้ายเพื่อแสดงข้อความในตัวแปรนั้นได้

ฉันได้อ่านข้อมูล sendMessage แล้ว แต่ทุกครั้งที่ฉันเพิ่มบรรทัดโค้ดลงในเพจ ดูเหมือนว่าจะทำให้ส่วนขยายเสียหาย ดังนั้นฉันจึงทำอะไรผิดอย่างแน่นอน

นี่คือโค้ดที่ไม่มีข้อมูล setBadgeText อยู่ในนั้น (กำลังทำงานอยู่)

getQueue.js

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 ด้วย

ขอบคุณ


person Brandon Wind    schedule 17.02.2015    source แหล่งที่มา


คำตอบ (1)


คุณต้องการรับส่งข้อความ

เอกสารประกอบดีในหัวข้อนี้ อย่างไรก็ตาม ภาพรวมโดยย่อ:

  1. หน้าส่วนขยาย1สามารถลงทะเบียน Listener สำหรับเหตุการณ์ chrome.runtime.onMessage ได้

  2. สคริปต์เนื้อหาเรียก chrome.runtime.sendMessage เพื่อเผยแพร่ข้อความ JSON-serializable ไปยังหน้าส่วนขยายทั้งหมดในส่วนขยายระดับบนสุด

1 ดูภาพรวมสถาปัตยกรรมนี้เพื่อดูคำจำกัดความที่ดีขึ้นของ "ส่วนขยาย" หน้าหนังสือ"

ฉันเน้นย้ำอย่างชัดเจนว่า "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 });
person Xan    schedule 17.02.2015