13 Mar 2024 11:17 AM - edited 14 Jan 2026 09:50 AM
Summary: Many applications now require an OTP for authentication. The following steps and snippet can be used to get the OTP from an API and populate it in a page.
1. Create synthetic monitor events up to the point where the one-time password (OTP) is needed.
2. Add a JavaScript event, using Add synthetic event, to fetch the OTP value and save the value. Something like the below, which stores the value in a variable called token.
api.startAsyncSyntheticEvent();
fetch('<yoururl>', {
method: 'POST',
headers: {
'content-type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'X-Requested-With'
}
}).then(function(response) {
if (!response.ok) {
throw Error(response.status + ":" + response.statusText);
}
return response;
}).then(response => response.text()).then(text => {
try {
api.info('Resp length: ' + text.length);
if (text.indexOf('code') >= 0) {
<your code to retrieve token>
api.setValue("token", token);
api.finish();
} else {
api.fail("Invalid Response");
}
} catch (err) {
api.fail("Failed to Execute");
}
}).catch(function(error) {
api.fail(error);
});
3. Add a second JavaScript event to pass the value to the OTP generation page
var pin = api.getValue("token");
document.querySelector("#PIN").value = pin;
4. Complete any other steps needed.
If these steps don't help, then open a chat and provide the following:
What to read next: