Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

trigger an error if the api script is not loaded #138

Merged
merged 7 commits into from
Jun 30, 2022
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
67 changes: 41 additions & 26 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,45 @@
const React = require('react');
const { generateQuery } = require("./utils.js");

// Create script to init hCaptcha
let onLoadListeners = [];
let apiScriptRequested = false;

// Generate hCaptcha API Script
const SCRIPT_ID = 'hcaptcha-api-script-id';
const HCAPTCHA_LOAD_FN_NAME = 'hcaptchaOnLoad';

// Prevent loading API script multiple times
let resolveFn;
let rejectFn;
const mountPromise = new Promise((resolve, reject) => {
resolveFn = resolve;
rejectFn = reject;
});

// Generate hCaptcha API script
const mountCaptchaScript = (params={}) => {
apiScriptRequested = true;
if (document.getElementById(SCRIPT_ID)) {
// API was already requested
return mountPromise;
}

// Create global onload callback
window.hcaptchaOnLoad = () => {
// Iterate over onload listeners, call each listener
onLoadListeners = onLoadListeners.filter(listener => {
listener();
return false;
});
};
window[HCAPTCHA_LOAD_FN_NAME] = resolveFn;

const domain = params.apihost || "https://js.hcaptcha.com";
delete params.apihost;

const script = document.createElement("script");
script.src = `${domain}/1/api.js?render=explicit&onload=hcaptchaOnLoad`;
script.id = SCRIPT_ID;
script.src = `${domain}/1/api.js?render=explicit&onload=${HCAPTCHA_LOAD_FN_NAME}`;
script.async = true;
script.onerror = (event) => {
console.error('Failed to load api: ' + script.src, event);
andrepolischuk marked this conversation as resolved.
Show resolved Hide resolved
rejectFn(new Error('Failed to load api'));
andrepolischuk marked this conversation as resolved.
Show resolved Hide resolved
}

const query = generateQuery(params);
script.src += query !== ""? `&${query}` : "";

document.head.appendChild(script);
}
return mountPromise;
};


class HCaptcha extends React.Component {
Expand All @@ -43,6 +54,7 @@ class HCaptcha extends React.Component {

// Event Handlers
this.handleOnLoad = this.handleOnLoad.bind(this);
this.handleOnLoadingError = this.handleOnLoadingError.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleExpire = this.handleExpire.bind(this);
this.handleError = this.handleError.bind(this);
Expand All @@ -62,17 +74,12 @@ class HCaptcha extends React.Component {
}
}

componentDidMount () { //Once captcha is mounted intialize hCaptcha - hCaptcha
componentDidMount () { // Once captcha is mounted intialize hCaptcha - hCaptcha
const { apihost, assethost, endpoint, host, imghost, languageOverride:hl, reCaptchaCompat, reportapi, sentry, custom } = this.props;
const { isApiReady } = this.state;

if (!isApiReady) { //Check if hCaptcha has already been loaded, if not create script tag and wait to render captcha
if (apiScriptRequested) {
return;
}

// Only create the script tag once, use a global variable to track
mountCaptchaScript({
if (!isApiReady) { // Check if hCaptcha has already been loaded, if not create script tag and wait to render captcha
const mountParams = {
apihost,
assethost,
endpoint,
Expand All @@ -83,10 +90,12 @@ class HCaptcha extends React.Component {
reportapi,
sentry,
custom
});
};

// Add onload callback to global onload listeners
onLoadListeners.push(this.handleOnLoad);
// Only create the script tag once, use a global promise to track
mountCaptchaScript(mountParams)
.then(this.handleOnLoad)
.catch(this.handleOnLoadingError);
} else {
this.renderCaptcha();
}
Expand Down Expand Up @@ -186,6 +195,12 @@ class HCaptcha extends React.Component {
});
}

handleOnLoadingError (event) {
const { onError } = this.props;

if (onError) onError(event);
}

andrepolischuk marked this conversation as resolved.
Show resolved Hide resolved
handleSubmit (event) {
const { onVerify } = this.props;
const { isRemoved, captchaId } = this.state;
Expand Down
22 changes: 21 additions & 1 deletion tests/hcaptcha.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ describe("hCaptcha", () => {
});


describe("Query parameter", () => {
describe("Mount hCaptcha API script", () => {

beforeEach(() => {
// Setup hCaptcha as undefined to load script
Expand Down Expand Up @@ -492,5 +492,25 @@ describe("hCaptcha", () => {
const script = document.querySelector("head > script");
expect(script.src).toContain("custom=true");
});

it("emits error when script is failed", async () => {
const onError = jest.fn();

instance = ReactTestUtils.renderIntoDocument(<HCaptcha
onError={onError}
sitekey={TEST_PROPS.sitekey}
/>);

const script = document.querySelector("head > script");
expect(onError.mock.calls.length).toBe(0);

script.onerror('api-script-failed');

// simulate microtask
await Promise.reject().catch(() => null)

expect(onError.mock.calls.length).toBe(1);
expect(onError.mock.calls[0][0]).toEqual(new Error('Failed to load api'));
});
});
});