Chrome 执行后台脚本后扩展程序更新扩展程序的视图

Chrome extension update extension'sview after execute background script

我想在扩展选项卡中显示 div 以及服务器的响应。 我的问题是 div 没有在我的 background.js.

中定义

我使用这段代码来执行一些功能:

  saveButton.addEventListener('click', async () => {
    let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

    chrome.scripting.executeScript({
      target: { tabId: tab.id },
      function: saveProperty,
     });
  });

我的问题是我的 div 没有在“saveProperty”函数中定义。

编辑

div 在扩展的选项卡中定义。

let showError = document.getElementById('showError');

saveProperty函数用于获取网页内容并保存到数据库软件中。

此扩展程序用于制作 webscraping

function saveProperty() {
  chrome.storage.sync.get(
    ['api_key', 'current_table'],

    [...]

    function sendData() {
      let req = new XMLHttpRequest();
      req.open("POST", url, true);
      req.setRequestHeader('Content-Type', 'application/json');
      req.addEventListener("load", function () {
        if (req.status >= 200 && req.status < 400) {

          // I get the error : showError is not defined.
          showError.textContent = 'Saved';
          showError.style = 'display:block';
          showError.style.backgroundColor = '#6dae24';
          setTimeout(function() {
            showError.style = 'display:none';
          }, 1500);

        } else {
          console.error(req.status + " " + req.statusText + " " + url);
          console.error(req.responseText);
        }
      });
      req.addEventListener("error", function () {
        console.error(req.responseText);
      });
      req.send(json);
    }
  });
}

非常感谢您的帮助!

executeScript 在自然没有 div 元素的不同页面(网页)中运行代码。

解决方案是在其页面中处理 div。例如,您的注入函数可以发送一条消息:

saveButton.addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({active: true, currentWindow: true});

  chrome.runtime.onMessage.addListener(function onMessage(msg, sender) {
    if (sender.tab?.id === tab.id) {
      chrome.runtime.onMessage.removeListener(onMessage);
      Object.assign(document.getElementById('showError'), msg.props);
    }
  });

  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    function: saveProperty,
  });
});

function saveProperty() {
  //............
  if (ok) {
    chrome.runtime.sendMessage({
      props: {
        textContent: 'Saved',
        style: 'display:block; background-color: #6dae24',
      },
    });
  }
}