Wednesday 30 June 2021

How to update HTML in inactive chrome tab with extension

I'm currently trying to make a Chrome extension, and I've ran into a problem where I don't know how to update HTML from an inactive tab. I'm trying to periodically access the HTML of a Google Meet in an inactive tab, to detect when people leave or join the call. However, document.querySelector only works when the tab is focused, as if it's not, it will just keep giving the same info from the last time it was focused, even if people have left or joined the call since then. Is there any way to detect these changes without having to focus the tab? Here is what I've tried in my code:

background.js

meetTab = []
// check for google meet tabs
function query()
{
    meetTab = []
    chrome.tabs.query({url: "https://meet.google.com/*-*"},function(tabs)
    {
        tabs.forEach(function(tab)
        {
            meetTab.push(tab)
        });
    })
}
chrome.tabs.onCreated.addListener(query)
chrome.tabs.onRemoved.addListener(query)
chrome.runtime.onStartup.addListener(query)
setInterval(send, 3000)
// execute script for each google meet tab every 3 sec
function send()
{

    meetTab.forEach(function(tab)
    {
        chrome.tabs.executeScript(tab.id, {file: "check.js"})
    })
}
// this part only prints updated info when meet tab is active
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    console.log(message)
});

check.js

// element to be tracked
thing = document.querySelector("#ow3 > div.T4LgNb > div > div:nth-child(9) > div.crqnQb > div.rG0ybd.xPh1xb.P9KVBf.LCXT6 > div.TqwH9c > div.SZfyod > div > div > div:nth-child(2) > div > div")
chrome.runtime.sendMessage({msg:thing.innerText})

manifest.json

{
  "manifest_version": 2,
  "name": "Meet Kicker",
  "version": "1.0",
  "icons": {"128": "bigicon.png"},
  "browser_action": {
    "default_icon": "smallicon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["storage", "tabs", "<all_urls>"],

  "background":
  {
    "scripts": [
      "background.js"
    ]
  }
}

Updated check.js trying to use MutationObserver

thing = document.querySelector("#ow3 > div.T4LgNb > div > div:nth-child(9) > div.crqnQb > div.rG0ybd.xPh1xb.P9KVBf.LCXT6 > div.TqwH9c > div.SZfyod > div > div > div:nth-child(2) > div > div")

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
            chrome.runtime.sendMessage({msg:thing.innerText})

      });
    });

observer.observe(thing, { characterData: true, attributes: false, childList: false, subtree: true });


from How to update HTML in inactive chrome tab with extension

No comments:

Post a Comment