Untitled

 avatar
unknown
plain_text
5 months ago
13 kB
6
Indexable
const profileSelector = document.getElementById("profile-selector");
const createProfileBtn = document.getElementById("create-profile");
const deleteProfileBtn = document.getElementById("delete-profile");
const fetchLinkedInDataBtn = document.getElementById("fetch-linkedin-data");
const form = document.getElementById("custom-field-form");
const fieldNameInput = document.getElementById("field-name");
const fieldValueInput = document.getElementById("field-value");
const fieldList = document.getElementById("field-list");
const mappingForm = document.getElementById("field-mapping-form");
const linkedinFieldSelect = document.getElementById("linkedin-field");
const formFieldNameInput = document.getElementById("form-field-name");
const mappingList = document.getElementById("mapping-list");
const jobTrackingForm = document.getElementById("job-tracking-form");
const companyNameInput = document.getElementById("company-name");
const jobTitleInput = document.getElementById("job-title");
const applicationDateInput = document.getElementById("application-date");
const applicationStatusInput = document.getElementById("application-status");
const jobTrackingList = document.getElementById("job-tracking-list");
const saveFormBtn = document.getElementById("save-form");
const savedFormsList = document.getElementById("saved-forms-list");
const exportDataBtn = document.getElementById("export-data");
const importDataBtn = document.getElementById("import-data");
const emailDataBtn = document.getElementById("email-data");
const hiddenFileInput = document.createElement("input"); // Hidden file input element
const autoFillButton = document.createElement("button");
hiddenFileInput.type = "file";
hiddenFileInput.accept = "application/json";

// Initialize Data on Popup Load
document.addEventListener("DOMContentLoaded", async () => {
  const data = await chrome.storage.local.get(["profiles", "activeProfile", "fieldMappings", "jobApplications", "savedForms"]);
  const profiles = data.profiles || {};
  const activeProfile = data.activeProfile || "Default";
  const fieldMappings = data.fieldMappings || {};
  const jobApplications = data.jobApplications || [];
  const savedForms = data.savedForms || [];

  // Ensure at least one profile exists
  if (!profiles[activeProfile]) {
    profiles[activeProfile] = {};
    await chrome.storage.local.set({ profiles, activeProfile });
  }

  updateProfileSelector(profiles, activeProfile);
  updateFieldList(profiles[activeProfile]);
  updateMappingList(fieldMappings);
  updateJobTrackingList(jobApplications);
  updateSavedFormsList(savedForms);
});

createProfileBtn.addEventListener("click", async () => {
  const profileName = prompt("Enter a name for the new profile:");
  if (!profileName) return;

  const data = await chrome.storage.local.get("profiles");
  const profiles = data.profiles || {};

  if (profiles[profileName]) {
    alert("Profile already exists!");
    return;
  }

  profiles[profileName] = {};
  await chrome.storage.local.set({ profiles });
  await chrome.storage.local.set({ activeProfile: profileName });
  updateProfileSelector(profiles, profileName);
  updateFieldList(profiles[profileName]);
});

deleteProfileBtn.addEventListener("click", async () => {
  const data = await chrome.storage.local.get(["profiles", "activeProfile"]);
  const profiles = data.profiles || {};
  const activeProfile = data.activeProfile;

  if (Object.keys(profiles).length === 1) {
    alert("You must have at least one profile.");
    return;
  }

  delete profiles[activeProfile];
  const newActiveProfile = Object.keys(profiles)[0];
  await chrome.storage.local.set({ profiles, activeProfile: newActiveProfile });
  updateProfileSelector(profiles, newActiveProfile);
  updateFieldList(profiles[newActiveProfile]);
});

profileSelector.addEventListener("change", async (e) => {
  const selectedProfile = e.target.value;
  const data = await chrome.storage.local.get("profiles");
  const profiles = data.profiles || {};
  await chrome.storage.local.set({ activeProfile: selectedProfile });
  updateFieldList(profiles[selectedProfile]);
});

// LinkedIn Data Extraction
fetchLinkedInDataBtn.addEventListener("click", async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  chrome.runtime.sendMessage({ action: "extractLinkedInData", tab }, (response) => {
    console.log(response);
    if (response?.success) {
      alert("LinkedIn data extracted and stored successfully!");
    } else {
      alert("Failed to extract LinkedIn data.");
    }
  });
});

// Customizable Fields
form.addEventListener("submit", async (e) => {
  e.preventDefault();

  const fieldName = fieldNameInput.value.trim();
  const fieldValue = fieldValueInput.value.trim();
  if (!fieldName || !fieldValue) return;

  const data = await chrome.storage.local.get(["profiles", "activeProfile"]);
  const profiles = data.profiles || {};
  const activeProfile = data.activeProfile;

  profiles[activeProfile][fieldName] = fieldValue;
  await chrome.storage.local.set({ profiles });
  fieldNameInput.value = "";
  fieldValueInput.value = "";
  updateFieldList(profiles[activeProfile]);
});

function updateFieldList(fields) {
  fieldList.innerHTML = "";
  for (const [name, value] of Object.entries(fields)) {
    const listItem = document.createElement("li");
    listItem.textContent = `${name}: ${value}`;
    fieldList.appendChild(listItem);
  }
}

// Field Mapping
mappingForm.addEventListener("submit", async (e) => {
  e.preventDefault();

  const linkedinField = linkedinFieldSelect.value;
  const formFieldName = formFieldNameInput.value.trim();
  if (!linkedinField || !formFieldName) return;

  const data = await chrome.storage.local.get("fieldMappings");
  const fieldMappings = data.fieldMappings || {};
  fieldMappings[formFieldName] = linkedinField;
  await chrome.storage.local.set({ fieldMappings });
  formFieldNameInput.value = "";
  updateMappingList(fieldMappings);
});

function updateMappingList(mappings) {
  mappingList.innerHTML = "";
  for (const [formField, linkedinField] of Object.entries(mappings)) {
    const listItem = document.createElement("li");
    listItem.textContent = `${linkedinField} : ${formField}`;
    const removeButton = document.createElement("button");
    removeButton.textContent = "Remove";
    removeButton.className = "remove-mapping-btn";
    removeButton.dataset.formField = formField; // Attach the form field as a data attribute
    listItem.appendChild(removeButton);
    mappingList.appendChild(listItem);
  }
}

// Remove Mapping Function
mappingList.addEventListener("click", async (e) => {
  if (e.target.classList.contains("remove-mapping-btn")) {
    const formFieldToRemove = e.target.dataset.formField;
    const data = await chrome.storage.local.get("fieldMappings");
    const fieldMappings = data.fieldMappings || {};
    delete fieldMappings[formFieldToRemove];
    await chrome.storage.local.set({ fieldMappings });
    updateMappingList(fieldMappings);
  }
});

// Job Application Tracking
jobTrackingForm.addEventListener("submit", async (e) => {
  e.preventDefault();

  const companyName = companyNameInput.value.trim();
  const jobTitle = jobTitleInput.value.trim();
  const applicationDate = applicationDateInput.value;
  const applicationStatus = applicationStatusInput.value;

  if (!companyName || !jobTitle || !applicationDate || !applicationStatus) return;

  const data = await chrome.storage.local.get("jobApplications");
  const jobApplications = data.jobApplications || [];
  jobApplications.push({
    companyName,
    jobTitle,
    applicationDate,
    applicationStatus
  });

  await chrome.storage.local.set({ jobApplications });
  companyNameInput.value = "";
  jobTitleInput.value = "";
  applicationDateInput.value = "";
  applicationStatusInput.value = "Applied";
  updateJobTrackingList(jobApplications);
});

function updateJobTrackingList(jobApplications) {
  jobTrackingList.innerHTML = "";
  jobApplications.forEach((job, index) => {
    const listItem = document.createElement("li");
    listItem.textContent = `${job.companyName} - ${job.jobTitle} - ${job.applicationDate} - ${job.applicationStatus}`;
    jobTrackingList.appendChild(listItem);
  });
}

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

  chrome.scripting.executeScript(
    {
      target: { tabId: tab.id },
      func: () => {
        const formData = {};
        document.querySelectorAll("form input, form select, form textarea").forEach((field) => {
          if (field.name || field.id) {
            formData[field.name || field.id] = field.value;
          }
        });
        return formData;
      }
    },
    async (results) => {
      const filledData = results[0].result;
      const data = await chrome.storage.local.get("savedForms");
      const savedForms = data.savedForms || [];
      savedForms.push({ date: new Date().toISOString(), formData: filledData });
      await chrome.storage.local.set({ savedForms });
      updateSavedFormsList(savedForms);
      alert("Form saved for future submissions!");
    }
  );
});

function updateSavedFormsList(savedForms) {
  savedFormsList.innerHTML = "";
  savedForms.forEach((form, index) => {
    const listItem = document.createElement("li");
    listItem.textContent = `Saved on ${new Date(form.date).toLocaleString()}`;
    savedFormsList.appendChild(listItem);
  });
}

exportDataBtn.addEventListener("click", async () => {
  const data = await chrome.storage.local.get();
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = "extension_data.json";
  a.click();
  URL.revokeObjectURL(url);
});

importDataBtn.addEventListener("click", () => {
  // Trigger the hidden file input dialog
  hiddenFileInput.click();
});

hiddenFileInput.addEventListener("change", async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = async (e) => {
    try {
      const importedData = JSON.parse(e.target.result);
      await chrome.storage.local.set(importedData);
      alert("Data imported successfully!");
      location.reload();
    } catch (error) {
      alert("Failed to import data. Please ensure the file is a valid JSON.");
    }
  };
  reader.readAsText(file);
});

emailDataBtn.addEventListener("click", async () => {
  const data = await chrome.storage.local.get();
  const jsonData = JSON.stringify(data, null, 2);
  const blob = new Blob([jsonData], { type: "application/json" });
  const reader = new FileReader();
  reader.onload = () => {
    const base64Data = reader.result.split(",")[1];
    const mailto = `mailto:?subject=Exported Data&body=Here is the exported data in base64 format.%0A%0A${base64Data}`;
    window.location.href = mailto;
  };
  reader.readAsDataURL(blob);
});

// Profile Selector Update
function updateProfileSelector(profiles, activeProfile) {
  profileSelector.innerHTML = "";
  Object.keys(profiles).forEach((profile) => {
    const option = document.createElement("option");
    option.value = profile;
    option.textContent = profile;
    option.selected = profile === activeProfile;
    profileSelector.appendChild(option);
  });
}
// Content Script to Inject Data into Forms
async function autofillForm() {
  const data = await chrome.storage.local.get(["profiles", "activeProfile", "fieldMappings"]);
  const profiles = data.profiles || {};
  const activeProfile = data.activeProfile || "Default";
  const fieldMappings = data.fieldMappings || {};
  const activeProfileData = profiles[activeProfile] || {};

  // Iterate over form elements
  document.querySelectorAll("form").forEach((form) => {
    form.querySelectorAll("input, textarea, select").forEach((field) => {
      const fieldName = field.name || field.id; // Use name or id as a fallback
      const mappedField = fieldMappings[fieldName];

      if (mappedField && activeProfileData[mappedField]) {
        // Check if field should be included based on user preference
        const includeField = confirm(`Fill ${fieldName} with "${activeProfileData[mappedField]}"?`);
        if (includeField) {
          field.value = activeProfileData[mappedField];
        }
      }
    });
  });
}

// Add Autofill Button to Web Pages
autoFillButton.textContent = "Auto Fill Form";
autoFillButton.style.position = "fixed";
autoFillButton.style.bottom = "20px";
autoFillButton.style.right = "20px";
autoFillButton.style.zIndex = "1000";
document.body.appendChild(autoFillButton);

// Attach Autofill Event
autoFillButton.addEventListener("click", () => {
  autofillForm().catch((err) => console.error("Error auto-filling form:", err));
});
Editor is loading...
Leave a Comment