Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions lib/src/loader.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { generateQuery, getFrame, getMountElement } from './utils';
import { HCAPTCHA_LOAD_FN_NAME, MAX_RETRIES, SCRIPT_ERROR, SENTRY_TAG } from './constants';
import { HCAPTCHA_LOAD_FN_NAME, MAX_RETRIES, SCRIPT_ERROR, SCRIPT_ID, SENTRY_TAG } from './constants';
import { initSentry } from './sentry';
import { fetchScript } from './script';

Expand All @@ -8,6 +8,25 @@ import type { ILoaderParams, SentryHub } from './types';
// Prevent loading API script multiple times
export const hCaptchaScripts = [];

// Tracks if the last load attempt failed (to allow automatic retries)
let lastLoadFailed = false;

export function resetLoader(scriptLocation?: HTMLElement) {
hCaptchaScripts.length = 0; // Clears promises

const element = getMountElement(scriptLocation);
const frame: any = getFrame(element);

const existingScript = frame.document.getElementById(SCRIPT_ID);
existingScript?.remove();

if (frame.window[HCAPTCHA_LOAD_FN_NAME]) {
delete frame.window[HCAPTCHA_LOAD_FN_NAME];
}

lastLoadFailed = false;
}

// Generate hCaptcha API script
export function hCaptchaApi(params: ILoaderParams = { cleanup: false }, sentry: SentryHub): Promise<any> {

Expand Down Expand Up @@ -108,7 +127,11 @@ export async function loadScript(params, sentry, retries = 0) {
const message = retries < MAX_RETRIES ? 'Retry loading hCaptcha Api' : 'Exceeded maximum retries';

try {
return await hCaptchaApi(params, sentry);
const result = await hCaptchaApi(params, sentry);

lastLoadFailed = false;

return result;
} catch (error) {

sentry.addBreadcrumb({
Expand All @@ -117,6 +140,8 @@ export async function loadScript(params, sentry, retries = 0) {
});

if (retries >= MAX_RETRIES) {
lastLoadFailed = true;

sentry.captureException(error);
return Promise.reject(error);
} else {
Expand All @@ -130,5 +155,15 @@ export async function loadScript(params, sentry, retries = 0) {
export async function hCaptchaLoader(params: ILoaderParams = {}) {
const sentry = initSentry(params.sentry);

// Resets state for fresh retry
if (lastLoadFailed) {
sentry.addBreadcrumb({
category: SENTRY_TAG,
message: 'Resetting loader after previous failure',
});

resetLoader(params.scriptLocation);
}

return await loadScript(params, sentry);
}
1 change: 1 addition & 0 deletions lib/src/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ onError?: (message) => void
if (onError) {
onError(script.src);
}
script?.remove();
onComplete(event, reject);
};

Expand Down