Execute javascript directly in the HTTP response

asp.net-mvc, http, javascript

Solution

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).

Problem

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-Type`to `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).

Original source

Related problems