From 0198780a3516584c61909a287a99b7ec877777d0 Mon Sep 17 00:00:00 2001 From: Mike Lei Date: Wed, 4 Jun 2025 12:33:06 +0800 Subject: [PATCH] fix code auto-pasting by using better heuristics to find the input box --- src/content.ts | 78 ++++++++++++-------------------------------------- 1 file changed, 19 insertions(+), 59 deletions(-) diff --git a/src/content.ts b/src/content.ts index 5ac1805c..63987008 100644 --- a/src/content.ts +++ b/src/content.ts @@ -283,69 +283,29 @@ async function qrDecode( } function pasteCode(code: string) { - const _inputBoxes = document.getElementsByTagName("input"); - const inputBoxes: HTMLInputElement[] = []; - for (let i = 0; i < _inputBoxes.length; i++) { - if ( - _inputBoxes[i].type === "text" || - _inputBoxes[i].type === "number" || - _inputBoxes[i].type === "tel" || - _inputBoxes[i].type === "password" - ) { - inputBoxes.push(_inputBoxes[i]); - } - } - if (!inputBoxes.length) { - return; - } - const identities = [ - "2fa", - "otp", - "authenticator", - "factor", - "code", - "totp", - "twoFactorCode", - ]; - for (const inputBox of inputBoxes) { - for (const identity of identities) { - if ( - inputBox.name.toLowerCase().indexOf(identity) >= 0 || - inputBox.id.toLowerCase().indexOf(identity) >= 0 - ) { - if (!inputBox.value || /^(\d{6}|\d{8})$/.test(inputBox.value)) { - inputBox.value = code; - fireInputEvents(inputBox); - } - return; - } - } - } + const selector = + "input[type=text], input[type=number], input[type=tel], input[type=password]"; + const isValidInput = (input: HTMLInputElement) => + input.checkVisibility() && + (!input.value || /^(\d{6}|\d{8}|[A-Z\d]{5})$/.test(input.value)); + let input: HTMLInputElement | undefined; - const activeInputBox = - document.activeElement && document.activeElement.tagName === "INPUT" - ? document.activeElement - : null; - if (activeInputBox) { - const inputBox = activeInputBox as HTMLInputElement; - if (!inputBox.value || /^(\d{6}|\d{8})$/.test(inputBox.value)) { - inputBox.value = code; - fireInputEvents(inputBox); - } - return; + if ( + document.activeElement && + document.activeElement.matches(selector) && + isValidInput(document.activeElement as HTMLInputElement) + ) { + input = document.activeElement as HTMLInputElement; + } else { + input = Array.from( + document.querySelectorAll(selector) + ).find(isValidInput); } - for (const inputBox of inputBoxes) { - if ( - (!inputBox.value || /^(\d{6}|\d{8})$/.test(inputBox.value)) && - inputBox.type !== "password" - ) { - inputBox.value = code; - fireInputEvents(inputBox); - return; - } + if (input) { + input.value = code; + fireInputEvents(input); } - return; } function fireInputEvents(inputBox: HTMLInputElement) {