Add custom fetcher option

This commit is contained in:
Ivan Nikolskiy 2025-06-09 20:07:28 +02:00
parent 0759b43efc
commit 7d3661f881
2 changed files with 23 additions and 4 deletions

View File

@ -19,6 +19,7 @@ This package, `django-hoptcha`, allows Django developers to quickly integrate Ho
* [Custom Rate-Limiting Logic](#custom-rate-limiting-logic)
* [Combining with Django-Ratelimit](#combining-with-django-ratelimit)
* [Custom CAPTCHA UI Rendering](#custom-captcha-ui-rendering)
* [Custom fetch function](#custom-fetch-function)
* [Customization](#customization)
* [License](#license)
@ -185,7 +186,17 @@ You can override the default iframe and style using the optional onCaptcha param
```javascript
hoptchaPost('/endpoint', payload, onSuccess, onError, function renderCustom(url) {
// Replace container with your custom implementation
$('#myCustomCaptchaArea').html(`<iframe src="${url}"></iframe>`);
document.getElementById('myCustomCaptchaArea').innerHTML = `<iframe src="${url}"></iframe>`;
});
```
### Custom fetch function
You can use custom fetch function to handle requests. This can be useful in cases where you want to pass custom headers like CSRF protection headers.
```javascript
configureHoptcha({
fetcher: fetchWithAuth
});
```

View File

@ -31,6 +31,10 @@
}
};
window.configureHoptcha = function ({ fetcher }) {
if (fetcher) window.hoptchaFetcher = fetcher;
};
/**
* Utility for retrying failed requests that require CAPTCHA.
* @param {string} url - The POST endpoint.
@ -39,8 +43,12 @@
* @param {function} [onError] - Error fallback.
* @param {function} [onCaptcha] - Optional custom render callback.
*/
window.hoptchaPost = function (url, payload, onSuccess, onError, onCaptcha) {
fetch(url, {
window.hoptchaPost = function (url,
payload,
onSuccess, onError, onCaptcha) {
const fetcher = window.hoptchaFetcher || fetch;
fetcher(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -71,7 +79,7 @@
// Register callback
window._captchaSuccessCallback = function (token) {
payload.captcha_token = token;
window.hoptchaPost(url, payload, onSuccess, onError, onCaptcha);
window.hoptchaPost(url, payload, onSuccess, onError, onCaptcha, fetcher);
};
const render = onCaptcha || window.renderCaptchaStep;