How to capture the response and override the appropriate headers in callback scriptWrapper?

13 hours ago 1
ARTICLE AD BOX

You cannot do this in the browser.

When you load a URL with:

const script = document.createElement('script'); script.src = METADATA_SOURCE + '?callback=scriptWrapper'; document.head.appendChild(script);

the browser treats that URL as a script resource. That means the remote server must respond with actual JavaScript, for example:

scriptWrapper({ ...data... });

and with a script MIME type such as:

Content-Type: application/javascript

In your case the response is coming back as:

Content-Type: application/json X-Content-Type-Options: nosniff

so the browser correctly refuses to execute it as a script.

Also, this part:

response.setHeader('X-Content-Type-Options', 'nosniff')

is not something you can do from client-side JavaScript. Response headers are set by the server that sends the response, not by the page that includes the script.

So there are only 3 real options:

Fix the remote endpoint to return JSONP
Example response body:

scriptWrapper({ ...data... });

with:

Content-Type: application/javascript

Use fetch() / XHR instead of <script> injection
This requires the remote server to allow CORS.

async function doGetMetaDataEvent() { const res = await fetch(METADATA_SOURCE); const data = await res.json(); scriptWrapper(data); }

Use your own backend/proxy
Your server fetches the remote JSON, then either:

returns it as JSON to your frontend, or

transforms it into JSONP if you really need callback-style loading.

So the answer to your question is: there is nowhere in scriptWrapper to “capture the response and override headers”. By the time scriptWrapper runs, the browser has already accepted or rejected the resource. Headers must be correct on the server side before the script is loaded.

Read Entire Article