DEV Community

Discussion on: How to auto verify OTP on the web using the new Web OTP API?

Collapse
 
sumit_1991 profile image
Sumit Kandoi • Edited

@jyotishman In your code implementation I have seen

const form = input.closest('form'); which form is this ?

When we are submitting form does it means after otp is autofilled it will redirect to next page

I have written below code but it's not submitting my custom form.
Do we need to give input.closest('form '); here for every case ?

Below is my code implementation for autofill otp

if ('OTPCredential' in window) {
window.addEventListener('DOMContentLoaded', e => {
const input = document.querySelector('input[autocomplete="one-time-code"]');
if (!input) return;
const ac = new AbortController();
const form = input.closest('firstInput');
if (form) {
form.addEventListener('submit', e => {
ac.abort();
});
}
navigator.credentials.get({
otp: {transport: ['sms']},
signal: ac.signal
}).then(otp => {
input.value = otp.code;

            console.log("Form Value ::::" + form);
            if (form) form.submit();
        }).catch(err => {
            console.log(err);
        });
    });
}
Enter fullscreen mode Exit fullscreen mode