DEV Community

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

Collapse
 
oceanrational profile image
VikramJS • Edited

Hey Jyotishman. I am using same for a while but it pop up everytime an sms having OTP received from different source like bank, zomatoetc.,

how can i prevent it. pop up everytime a new OTP SMS received.
I tried on button clicked but no luck.

with correct domain name
dev-to-uploads.s3.amazonaws.com/i/...

with wrong domain name.
dev-to-uploads.s3.amazonaws.com/i/...

Collapse
 
jyotishman profile image
Jyotishman Saikia

hi, Can you send the sample code so i that i can assist u better where you might be wrong.

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?