-2

There is a webpage that constantly (every 100oms) log out a variable called "t", which is a json type. My goal is get the content of t variable in content.js (or some other injection method), pass it to background.js or popup.js and show up popup.html. it needs to run at same pace, like 1000ms as the t variable refresh every 1 second.

I am stucked at first step, i don't know how to get the variable in the main page. i do found some post have similar topic like this one: Access global js variables from js injected by a chrome extension, but i need more detailed implementation.

wzboss
  • 17
  • 5

1 Answers1

1

Here is a sample of it.

enter image description here

manifest.json

{
  "name": "hoge",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": [
    "scripting"
  ],
  "host_permissions": [
    "<all_urls>"
  ],
  "action": {
    "default_popup": "popup.html"
  }
}

popup.html

<html>
<body>
  <div id="div"></div>
  <script src="popup.js"></script>
</body>
</html>

popup.js

const getHoge = () => {
  return t;
}

const main = async () => {
  while (1) {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.scripting.executeScript({
        target: { tabId: tabs[0].id, },
        world: "MAIN",
        func: getHoge
      }, (result) => {
        document.getElementById("div").innerText = result[0].result;
      });
    });

    await new Promise(r => setTimeout(r, 500));
  }
}

main();

test web page

<html>
<body>
  <div id="div">
    </divz>
    <script>
      let t;
      let i = 0;
      let div = document.getElementById("div");

      const main = async () => {
        while (1) {
          t = JSON.stringify({ i: i });
          div.innerText = t;
          await new Promise(r => setTimeout(r, 1000));
          i++;
        }
      }

      main();
    </script>
</body>
</html>
Norio Yamamoto
  • 1,495
  • 2
  • 3
  • 10
  • Thanks for reply. It gives me error when i load to Chrome: Error handling response: TypeError: Cannot read properties of undefined (reading '0') the line that heighted is document.getElementById("div").innerText = result[0].result; – wzboss May 01 '23 at 17:45
  • Did you remove "
    " from my popup.html?
    – Norio Yamamoto May 01 '23 at 22:51
  • thanks, it worked on your page, i was test on my other page which is slightly different. – wzboss May 02 '23 at 00:23
  • You had a extra z in div box in HTML code, line 4: "". – wzboss May 02 '23 at 15:59