DEV Community

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

Collapse
 
oceanrational profile image
VikramJS • Edited

This is form page.


< form action="ok.html" method="POST" >

< input type="number" class="form-control" id="mobileNo" placeholder="10 Digit Mobile No">

< button class="btn btn-primary" onfocus="test()" name="sendOTP">Validate

< input type="text" class="form-control" id="OTP" placeholder="OTP" autocomplete="one-time-code">

< button class="btn btn-primary btn-style" id="validateOTP">Verify
< /form>

And this is script.

function test(){


if ('OTPCredential' in window) {

console.log("in OTPCredentials");

window.addEventListener("DOMContentLoaded", e => {

const input = document.querySelector('input[autocomplete="one-time-code"]');

const button = document.querySelector("button[type='submit']");

if (!input) return;

const ac = new AbortController();

const form = input.closest('form');

if (form) {

form.addEventListener('submit', e => {

console.log("ac.abort() is called");

ac.abort();

});

}

console.log("WebOTP API is called");

navigator.credentials.get({

otp: { transport:['sms'] },

signal: ac.signal

}).then(otp => {

input.value = otp.code;

if (form) form.submit();

console.log("submit() is called");

navigator.credentials.preventSilentAccess();

}).catch(err => {

console.log(err);

});

});

}

const message = document.querySelector('#message');

message.innerText = Your OTP is: 123456.\n@${window.location.host} #123456;

}

Thread Thread
 
sumit_1991 profile image
Sumit Kandoi

@oceanrational : I have one doubt on your above code why you gave

const form = input.closest('form');
form id should come instead of form. What do you think?