Get value of OTP one time code in moblie browser JS

1.4k Views Asked by At

Testing on iPhone, iOS 16. Chrome & Firefox browsers.

I'm creating a page with one time password form, which consists of 6 inputs. When user is on this page, he/she will get a SMS with OTP code. I would like to auto fill those inputs once SMS is received, so user is not bothered (in Mobile version of course).

My question is - is there way to get/read the code from SMS when its received? Is there an event that I can listen to, to read it? If not, what can be another solution here?

What I've tried

  1. WebOTAPI - TBH I don't get does it work. I've tried this, but seems like its never been triggered. OTPCredential object exists in Window but nothing happens.

    if ('OTPCredential' in window) {
     window.addEventListener('DOMContentLoaded', () => {
       const input = document.querySelector('input[autocomplete="one-time-code"]') as HTMLInputElement;
       if (!input) return;
       const ac = new AbortController();
    
       navigator.credentials
         .get({
           otp: { transport: ['sms'] },
           signal: ac.signal,
         })
         .then((otp: any) => {
           console.log(otp));
           input.value = otp.code;  // <-- never got here (-_-)
         })
         .catch((err) => {
           console.log(err);
         });
     });
    

    }

  2. I've tried different inputs like

    <input id="single-factor-code-text-field" autocomplete="one-time-code" />
    
    <input type="text" inputmode="numeric" autocomplete="one-time-code" pattern="\d{6}" required />
    
    <!-- also like this -->
    <input type="text" name="token[0]" inputmode="decimal" id="token[0]" maxlength="6" autocomplete="one-time-code">
    <input type="text" name="token[1]" inputmode="decimal" id="token[1]" maxlength="6" autocomplete="one-time-code">
    <input type="text" name="token[2]" inputmode="decimal" id="token[2]" maxlength="6" autocomplete="one-time-code">
    <input type="text" name="token[3]" inputmode="decimal" id="token[3]" maxlength="6" autocomplete="one-time-code">
    <input type="text" name="token[4]" inputmode="decimal" id="token[4]" maxlength="6" autocomplete="one-time-code">
    <input type="text" name="token[5]" inputmode="decimal" id="token[5]" maxlength="6" autocomplete="one-time-code">
    

Such inputs only get filled if user clicks on input and then clicks on code hint. As I mentioned, I would like to auto fill the code.

enter image description here

  1. I've tried ClipboardEvent but it also never triggers.

How this can be solved? Ideally listening to the event which has OTP code would be perfect (then I can easily auto fill inputs). Any help will be appreciated.

0

There are 0 best solutions below