ai_forms / content.js
kpgu's picture
Upload 6 files
b63d833 verified
Raw History Blame Contribute Delete
2.62 kB
// content.js
async function autoFillForms() {
console.log("Auto-fill started.");
let questionElements = document.querySelectorAll('.office-form-question-title');
if (questionElements.length === 0) {
questionElements = document.querySelectorAll('.office-form-question-title-format-choice');
}
if (questionElements.length === 0) {
questionElements = document.querySelectorAll('[aria-labelledby*="question-title"]');
}
console.log("Question Elements:", questionElements);
const questions = Array.from(questionElements).map(el => el.textContent.trim());
console.log("Questions:", questions);
for (let i = 0; i < questions.length; i++) {
const question = questions[i];
try {
const answer = await getGoogleAnswer(question); // Use Google API here
if (answer) {
const inputFields = document.querySelectorAll('input[type="text"], textarea');
console.log("Input Fields:", inputFields);
if (inputFields[i]) {
console.log("Setting input field:", i, "to:", answer);
inputFields[i].value = answer;
} else {
const radioButtons = document.querySelectorAll('input[type="radio"]');
console.log("Radio Buttons:", radioButtons);
radioButtons.forEach(radio => {
console.log("Radio Label:", radio.parentElement.textContent);
if (radio.parentElement.textContent.includes(answer)) {
console.log("Checking Radio Button:", radio);
radio.checked = true;
}
});
}
}
} catch (error) {
console.error("Error fetching answer:", error);
}
}
}
async function getGoogleAnswer(question) {
console.log("Fetching Google answer for:", question);
const apiKey = "YOUR_GOOGLE_CUSTOM_SEARCH_API_KEY"; // Replace with your API key
const searchEngineId = "YOUR_GOOGLE_SEARCH_ENGINE_ID"; // Replace with your search engine ID
const apiUrl = `https://www.googleapis.com/customsearch/v1?key=${apiKey}&cx=${searchEngineId}&q=${encodeURIComponent(question)}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
console.log("Google API Response:", data);
if (data.items && data.items.length > 0) {
return data.items[0].snippet || data.items[0].title; // Extract snippet or title
} else {
return "Answer not found on Google.";
}
} catch (error) {
console.error("Google API error:", error);
return "Error fetching from Google.";
}
}
window.addEventListener('load', autoFillForms);