Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute javascript directly in the HTTP response

Some years ago I wrote a system where I'm pretty sure that I was able to execute javascript directly from the HTTP response.

What I did was to set the Content-Typeto application/javascript and then simply include the script in the response body.

Now I'm trying to do the same thing with just a simple alert: alert('Hello world'); as the HTTP response body. But the browser doesn't execute the script but just treats it as text.

Am I doing something wrong, or have it never been possible? (It's not an ajax request).

like image 605
jgauffin Avatar asked Dec 05 '25 14:12

jgauffin


1 Answers

This is how JSONP works. Simply add a <script /> tag, whose src is set to the remote script your want to execute, and you'll be good to go.

In your application:

var tag = document.createElement("script");

tag.src = "/your-remote-page/";
document.getElementsByTagName("head")[0].appendChild(tag);

/your-remote-page:

alert("Hi");

For more info on JSONP, see Can anyone explain what JSONP is, in layman terms?

If you have a response which conditionally returns either a file or a JavaScript response, then I'm not aware of a way you can either let the user download the file, or execute the JavaScript. The methods used to handle those responses are mutually exclusive. Either you inject a <script /> tag (for JavaScript), or submit a form/ anchor (file download).

like image 55
Matt Avatar answered Dec 07 '25 02:12

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!