auto read SMS/OTP in react PWA

Viewed 6986

I am working on a login process using OTP for a PWA built-in using react.

I want to auto-fill my OTP. I was wondering if anyone knew something that could lead me in the right direction about this.

3 Answers

There is a draft specification for a Web OTP API.

The Web OTP API lets your app receive specially-formatted messages bound to your app's origin. From this, you can programmatically obtain an OTP from an SMS message and verify a phone number for the user more easily.

https://web.dev/web-otp/

Just to be sure sms should be in correct format. Below is the code which i put into componentDidMount and it works.

import "./styles.css";

import React from "react";

export default class App extends React.Component {
  state = {
    otp: ""
  };

componentDidMount() {

if ("OTPCredential" in window) {
  const ac = new AbortController();

  navigator.credentials
    .get({
      otp: { transport: ["sms"] },
      signal: ac.signal
    })
    .then((otp) => {
      this.setState({ otp: otp.code });
      ac.abort();
    })
    .catch((err) => {
      ac.abort();
      console.log(err);
    });
}


}

  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Your OTP is: {this.state.otp}</h2>
      </div>
    );
  }
}

It always prompt whenever a sms received.enter image description here

And will display otp on screen. enter image description here

Open the CodeSandbox link in chrome mobile browser and send the below sms to your device

Hi this is a login otp: 9299
@t0hj4.csb.app #9299
Related