diff --git a/src/dataurl.ts b/src/dataurl.ts index 13bc8b43..17711629 100644 --- a/src/dataurl.ts +++ b/src/dataurl.ts @@ -81,9 +81,12 @@ export async function resourceToDataURL( let dataURL: string try { + const requestInit = options.fetchRequestInit + ? options.fetchRequestInit + : options.fetchRequestInitGenerator?.(resourceUrl) const content = await fetchAsDataURL( resourceUrl, - options.fetchRequestInit, + requestInit, ({ res, result }) => { if (!contentType) { // eslint-disable-next-line no-param-reassign diff --git a/src/embed-webfonts.ts b/src/embed-webfonts.ts index 42c73da6..c33b514c 100644 --- a/src/embed-webfonts.ts +++ b/src/embed-webfonts.ts @@ -35,14 +35,13 @@ async function embedFonts(data: Metadata, options: Options): Promise { url = new URL(url, data.url).href } - return fetchAsDataURL<[string, string]>( - url, - options.fetchRequestInit, - ({ result }) => { - cssText = cssText.replace(loc, `url(${result})`) - return [loc, result] - }, - ) + const requestInit = options.fetchRequestInit + ? options.fetchRequestInit + : options.fetchRequestInitGenerator?.(url) + return fetchAsDataURL<[string, string]>(url, requestInit, ({ result }) => { + cssText = cssText.replace(loc, `url(${result})`) + return [loc, result] + }) }) return Promise.all(loadFonts).then(() => cssText) diff --git a/src/types.ts b/src/types.ts index b511363f..44c1716b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -91,4 +91,12 @@ export interface Options { * */ fetchRequestInit?: RequestInit + + /** + * Function that generates a RequestInit based on a given URL. + * This function is intended to provide a convenient way to customize the RequestInit configuration for + * fetching the data from a specific URL. + * + */ + fetchRequestInitGenerator?: (url: string) => RequestInit | undefined } diff --git a/test/spec/options.spec.ts b/test/spec/options.spec.ts index ab40ffa2..68ded1d6 100644 --- a/test/spec/options.spec.ts +++ b/test/spec/options.spec.ts @@ -173,4 +173,19 @@ describe('work with options', () => { .then(done) .catch(done) }) + + it('should support fetchRequestInitGenerator', (done) => { + bootstrap('images/node.html', 'images/style.css') + .then( + assertTextRendered(['PNG', 'JPG'], { + fetchRequestInitGenerator: (url: string) => { + return url.includes("/test") + ? { credentials: 'include' } as RequestInit + : undefined + }, + }), + ) + .then(done) + .catch(done) + }) })