Home > front end >  How can I use an extension context variable in the browser context?
How can I use an extension context variable in the browser context?

Time:02-22

I'm trying to pass startDate and endDate to my chrome extension script but it doesn't work for some reason. I checked out the chrome extension documentation but I couldn't find any solution except for using the args property in chrome.scripting.executeScript. Nevertheless, it serializes the arguments so I can't actually use them.

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);
}

CodePudding user response:

Fixed it by pulling the dates from the addEventListener function rather than the global scope. I thought I was passing the values to the addEventListener function in async (startDate, endDate) but they were only the function parameters names.

Solution:

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);
}
  • Related