AHD Chrome Extension

A script for linking data and handling forms on specific websites

As of 2024-05-17. See the latest version.

// ==UserScript==
// @name         AHD Chrome Extension
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  A script for linking data and handling forms on specific websites
// @match        *://*/*
// @license MIT
// @grant        none
// ==/UserScript==




//🍉CONFIG🍉

const VERSION=2; // for updates

const texasWebsiteFormNames = [
  "applicantInformationForm",
  "applicantAddressesForm",
  "lifelineQualificationForm",
  "lifelineEligibilityForm",
  "agreementsForm",
  "proofForm",
];


//🍉HELPER🍉

function leaveStamp(){
    const elem = document.createElement("div");
    elem.innerText="ahd extension";
    elem.id='ahdahdahd'
    elem.innerText=JSON.stringify({VERSION})
    elem.style.display='none'
    document.body.insertBefore(elem, document.body.firstChild);
}

function convertListToObjects(list) {
  const result = {};
  list.forEach((obj) => {
    const { key, ...rest } = obj;
    result[key] = { key, ...rest };
  });
  return result;
}

function logFormData(form) {
  if (!form || !(form instanceof HTMLFormElement)) {
    console.error("Invalid or missing form reference.");
    return;
  }

  const formData = Array.from(form.elements)
    .filter((element) => element.name)
    .map((element) => {
      const label = form.querySelector(`label[for="${element.id}"]`) || {
        innerText: "No label found",
      };
      return {
        key: element.name,
        value: element.value,
      };
    });

  console.log("Form Data:", JSON.stringify(formData, null, 2));
  return convertListToObjects(formData);
}

async function getElementAsync(query) {
  return new Promise((resolve) => {
    const intervalId = setInterval(() => {
      const element = document.querySelector(query);
      console.log("Trying to get element by id", query, element);
      if (element) {
        clearInterval(intervalId);
        resolve(element);
      }
    }, 1000);
  });
}

async function sendDataToParent(data) {
  console.log("sending data to parent", data);
  window.parent.postMessage({ data, sent_by_ext: true }, "*");
}



//🍉TEXAS LIFELINE SCRIPT🍉

let link_data = {};
const saveFormsData = async () => {
  console.log(link_data);
  const id = document.getElementById("link_id")?.innerText;
  if (!id || id === "") return alert("ID NOT LINKED. REPORT TO ADMINS!!");
  let data = {};
  texasWebsiteFormNames.forEach((formName) => {
    const form = document.forms[formName];
    if (form) {
      console.log(`Data for ${formName}:`);
      data = { ...data, ...logFormData(form) };
    } else {
      console.log("Form not found.");
    }
  });
  sendDataToParent(data);
};

const runTexasLifelineScript = async () => {
  const intervalId = setInterval(() => {
    const originalButton = document.querySelector("button.btn.btn-success");
    if (originalButton) {
      clearInterval(intervalId);

      originalButton.style.display = "none";

      const newButton = document.createElement("button");
      newButton.type = "button";
      newButton.innerHTML = `
      <div style="font-weight: bold; text-align: center;">
          Submit Complete Application
      </div>`;
      newButton.className = "btn btn-primary";

      originalButton.parentNode.insertBefore(newButton, originalButton);

      newButton.addEventListener("click", async function () {
        await saveFormsData();
        console.log("Custom function called!");

        originalButton.click();
      });
    } else {
      console.log("Checking for the original button...");
    }
  }, 1000);
};


//🍉DTA CONNECT🍉



async function runDtaConnectScript() {
  const form = await getElementAsync("#about-me");
  const next_btn = await getElementAsync("button[form='about-me']");
  const submit_btn = await getElementAsync("#id-1-1");
  let data = logFormData(form);
  sendDataToParent(data);
}

//🍉MAIN FUNCTION🍉


window.addEventListener("message", (event) => {
    console.log("event", event.data)
  if (event.data?.sent_by_ahd) {
    console.log("LINKING DATA", event.data);
    const link_data = event.data ?? {};
    const notification = document.createElement("div");
    notification.style =
      "z-index:1000; zoom:0.8; position: fixed; top: 0px; right: 0px; background-color: #f8d7da; color: #721c24; padding: 10px; border: 1px solid #f5c6cb; border-radius: 5px;";
    notification.innerHTML = `
        <p>Website under control by AHD</p>
        <p>User ID Link: <span id='link_id'>${link_data.id}</span></p>
        `;
    document.body.insertBefore(notification, document.body.firstChild);
  }
});

function __main__() {
  console.log("🚀 AHD CHROME EXTENSION IS WORKING!");
  leaveStamp();
  const url = window.location.href;
  if (url === "https://www.texaslifeline.org/createorder/") {
    runTexasLifelineScript();
  } else if (url === "https://dtaconnect.eohhs.mass.gov/applyTafdc") {
    runDtaConnectScript();
  }
}

setTimeout(__main__, 1000);