Detect OTPs in your Angular App from your mobile SMS

Tushar Upadhyay
Level Up Coding
Published in
2 min readFeb 2, 2023

--

Image credit: Freepik

Native andriod apps can automatically detect and autofill OTPs but do you know we can do exact same thing in web applications?

We have WebOtpApi in Javascript which can be used to detect the OTP SMS. We will use this api and wrap it with a angular directive so that we can use it in any input component to listen to OTP messages.

Lets make a directive:

Add this directive in your declarations array in your app.module.ts.

Now to use this, just add appWebOtp directive to any input component you want to auto fill.

<input appWebOtp placeholder="Enter OTP"/>

SMS format:

You must use following SMS format. Just send this to your mobile and you will see a popup to autofill the OTP if you have opened the web app on chrome mobile. In case of desktop , if chrome has same google account as your android then you will get a notification on android to submit the OTP to the web app.
NOTE: It really doesn’t matter who sent this sms, this api will only look for the host address (after `@`)

Your OTP is: 123456.

@www.example.com #123456

For more about WebOtpApi please refer to https://web.dev/web-otp/.

I have also made an npm package for this. To directly use this in your app, you can check out https://www.npmjs.com/package/web-otp-angular.

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job

--

--