UNPKG

@transferwise/approve-api-action-helpers

Version:

An http client that handles SCA protected requests gracefully

41 lines (34 loc) 1.17 kB
/* eslint-disable fp/no-mutation */ import { MESSAGE_SUCCESS, MESSAGE_FAILED, MESSAGE_CLOSED } from './config'; import { createForm } from './createForm'; export function tabFlow({ token, approvalPageUrl, resolve, reject }) { // 1. creates a new form, but doesn't submit it yet const name = 'tw-approve-api-action'; const form = createForm({ target: name, token, approvalPageUrl, flow: 'tab' }); // eslint-disable-next-line unicorn/prefer-dom-node-append document.body.appendChild(form); // 2. opens the approval page in new tab const approvalPage = window.open(approvalPageUrl, name); // 3. submit the form (will POST to this new tab) form.submit(); const handleEvents = (event) => { // eslint-disable-next-line default-case switch (event.data) { case MESSAGE_SUCCESS: closeTab(); resolve(); return; case MESSAGE_FAILED: closeTab(); reject(); return; case MESSAGE_CLOSED: closeTab(); } }; const closeTab = () => { approvalPage.close(); window.removeEventListener('message', handleEvents); }; window.addEventListener('message', handleEvents); }