0% found this document useful (0 votes)
48 views3 pages

Async Function

The provided JavaScript function handles a keydown event to extract question text and options from a web page when the 'Alt + X' keys are pressed. It collects any images associated with the question, formats the text accordingly, and copies it to the clipboard. The function then makes an API call to Google Gemini to generate an answer, checks if it matches any of the provided options, and either selects the correct option or displays the answer in a specified area if no match is found.

Uploaded by

uc006283
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views3 pages

Async Function

The provided JavaScript function handles a keydown event to extract question text and options from a web page when the 'Alt + X' keys are pressed. It collects any images associated with the question, formats the text accordingly, and copies it to the clipboard. The function then makes an API call to Google Gemini to generate an answer, checks if it matches any of the provided options, and either selects the correct option or displays the answer in a specified area if no match is found.

Uploaded by

uc006283
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

async function handleKeyDown(t) {

if (t.altKey && "x" === t.key.toLowerCase()) {


const questionElement = document.querySelector("#QuestionRow");
const optionsElement = document.querySelector("#optionCol");

if (questionElement && optionsElement) {


// Extract question text and images
const questionText = questionElement.innerHTML.trim();
const options = optionsElement.querySelectorAll('label');

const tempDiv = document.createElement("div");


tempDiv.innerHTML = questionText;

// Collect images
const images = tempDiv.querySelectorAll("img");
let imageSources = [];
for (let img of images) {
if (img.src) {
const src = img.src.startsWith("http://") ? img.src.replace("http://",
"https://") : img.src;
imageSources.push(src);
}
}

// Format the text for image-based and textual questions differently


let textToCopy;
if (imageSources.length > 0) {
// If there are images, format it as an image-based question
const imagesList = imageSources.join("\n");
textToCopy = `${tempDiv.innerText}\nImage(s):\n${imagesList}\nOptions:\n$
{[...options].map(option => option.innerText.trim()).join(", ")}\nSelect the
correct option from the options above and make sure that answer is correct. Provide
only the option text as the answer.`;
} else {
// If no images, format it as a textual question
textToCopy = `${tempDiv.innerText}\nOptions:\n${[...options].map(option =>
option.innerText.trim()).join(", ")}\nSelect the correct option from the options
above and make sure that answer is correct. Provide only the option text as the
answer.`;
}

// Copy text to clipboard


await copyTextToClipboard(textToCopy);
console.log(textToCopy);

// API call to Google Gemini


try {
const response = await
fetch('https://generativelanguage.googleapis.com/v1beta/models/gemini-
pro:generateContent?key=AIzaSyASPaWGXdaEasguLguCkadACzRnJdn8n38', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
contents: [{
parts: [{
text: textToCopy
}]
}]
}),
});

const data = await response.json();


const answer = data.candidates[0].content.parts[0].text.trim();

// Validation: Check if the API's answer matches any of the options


let matchedOption = null;
options.forEach(option => {
const optionText = option.innerText.trim();
if (optionText === answer) {
matchedOption = option;
}
});

if (matchedOption) {
const radioButton = matchedOption.querySelector('input[type="radio"]');
if (radioButton) {
radioButton.checked = true; // Check the radio button corresponding to
the answer
const event = new Event('change', { bubbles: true });
radioButton.dispatchEvent(event);
console.log("Selected option checked:", answer);
}
} else {
// Display the answer in a specified area if it doesn't match any option
const displayArea = document.querySelector("#header > nav > div.col-md-
4.col-sm-4.col-xs-12 > ul > li");
if (displayArea) {
const originalHTML = displayArea.innerHTML;
displayArea.innerHTML = answer; // Show the answer
setTimeout(() => {
displayArea.innerHTML = originalHTML; // Restore original content
after 2 seconds
}, 2000);
console.log("Displayed answer in the specified area:", answer);
} else {
console.error('Display area not found.');
}
}

} catch (error) {
console.error('Error during API call:', error);
}
} else {
console.warn("Question element or option column not found.");
}
}
}

async function copyTextToClipboard(t) {


try {
if (!t) throw new Error("Text not found");
await navigator.clipboard.writeText(t), console.log("Text copied to clipboard
successfully.");
} catch (t) {
console.error("Failed to copy text to clipboard:", t);
}
}

document.addEventListener("keydown", handleKeyDown);

You might also like