Getting "DOMException: OTP retrieval was cancelled." when using WebOTP API

658 Views Asked by At

I am testing WebOTP API for autofilling verification code using WebOTP API.

I'm trying to fill an HTML input element inside a cross-origin iframe. The iframe is a Preact app.

I added the following to the iframe code where the input lives:

useEffect(() => {
    if ('OTPCredential' in window) {
        const input = document.querySelector<HTMLInputElement>(
            'input[name="code-input-0"]',
        );
        if (!input) return;
        const ac = new AbortController();
        navigator.credentials
            .get({
                otp: { transport: ['sms'] },
                signal: ac.signal,
            })
            .then(otp => {
                input.value = otp!.code;
                ac.abort();
            })
            .catch(err => {
                console.error(err);
                ac.abort();
            });
    }
});

To support cross-origin iframes, I added allow='otp-credentials' attribute to the iframe tag.

However, when I navigate to the page with the input, I see DOMException: OTP retrieval was cancelled. in the console. When I send the text message, I see the prompt overlay asking to allow Chrome to read the message and enter the code. When I select "Allow", nothing happens.

The text format I sent is:

Your OTP is: 12345
@top-level-domain.com #12345 @iframe-domain.com

The text format seems to be fine since it's prompting the overlay. But I'm not sure why the DOMException is occurring on page load. Any insight on why this is happening would be greatly appreciated.

1

There are 1 best solutions below

1
Анатолий Иванов On

I think you should check this article: https://developer.mozilla.org/en-US/docs/Web/API/WebOTP_API#controlling_access_to_the_api

Maybe you just forgot to add "src" attribute to iframe or set Permissions-Policy header For example: HTTP:

Permissions-Policy: otp-credentials=(self "https://embedded.com")

HTML:

<iframe src="https://embedded.com/..." allow="otp-credentials"> ... </iframe>