如何在浏览器上下文中使用扩展上下文变量?

How can I use an extension context variable in the browser context?

我正在尝试将 startDateendDate 传递到我的 chrome 扩展脚本,但由于某种原因它不起作用。我查看了 chrome 扩展文档,但除了使用 chrome.scripting.executeScript 中的参数 属性 外,我找不到任何解决方案。然而,它序列化了参数,所以我不能实际使用它们。

const startDate = document.getElementById("start-date")?.value;
const endDate = document.getElementById("end-date");
const searchButton = document.getElementById("search-button");

searchButton.addEventListener("click", async (startDate, endDate) => {
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    args: [startDate],
    function: scrapCalendar,
  });
});

function scrapCalendar(startDate) {
  let pageDateRange = document
    .querySelector(
      "#sectionBody > div.con_cuer > div.tabla1 > div:nth-child(2) > div.tabder"
    )
    ?.innerText.split(" ");
  /*
  let goLastPageButton = document.querySelector(
    "#sectionBody > div.con_cuer > div.flechas_horario > div.izq"
  );
  let goNextPageButton = document.querySelector(
    "#sectionBody > div.con_cuer > div.flechas_horario > div.der"
  );*/
  let pageStartDate = pageDateRange[1];
  let pageEndDate = pageDateRange[3];
  console.log(startDate);
  console.log(pageStartDate + " - " + pageEndDate);
}

通过从 addEventListener 函数而不是全局范围中提取日期来修复它。我以为我将值传递给 async (startDate, endDate) 中的 addEventListener 函数,但它们只是函数参数名称。

解决方案:

const searchButton = document.getElementById("search-button");

searchButton.addEventListener("click", async () => {
  const startDate = document.querySelector("#start-date")?.value;
  const endDate = document.querySelector("#end-date")?.value;
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    args: [startDate, endDate],
    func: scrapCalendar,
  });
});

function scrapCalendar(startDate, endDate) {
  let pageDateRange = document
    .querySelector(
      "#sectionBody > div.con_cuer > div.tabla1 > div:nth-child(2) > div.tabder"
    )
    ?.innerText.split(" ");
  /*
  let goLastPageButton = document.querySelector(
    "#sectionBody > div.con_cuer > div.flechas_horario > div.izq"
  );
  let goNextPageButton = document.querySelector(
    "#sectionBody > div.con_cuer > div.flechas_horario > div.der"
  );*/
  let pageStartDate = pageDateRange[1];
  let pageEndDate = pageDateRange[3];
  console.log(startDate + " * " + endDate);
  console.log(pageStartDate + " - " + pageEndDate);
}