3

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

jgauffin
  • 99,844
  • 45
  • 235
  • 372

1 Answers1

4

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

Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180
  • Not possible. The response is conditinal depending on the incoming data. It can either be a file or a javascript. – jgauffin May 28 '14 at 08:36
  • @jgauffin: The response can either be a file or a JavaScript? That doesn't sound very consistent... – Cerbrus May 28 '14 at 08:37
  • @Cerbrus: It's not my system. I'm just helping. There is a large calculation going on where some cases required additional verification from the user. They do not want to redo everything as the most common case generates the PDF. – jgauffin May 28 '14 at 08:39
  • @jgauffin: _"It's not my system"_: Yea, that explains that :-) – Cerbrus May 28 '14 at 08:40
  • @jgauffin: If my answer isn't possible, then I'm AFAIK, you're out of options. – Matt May 28 '14 at 08:43
  • @Matt: That will blank the page. That's why I wanted to use `content-type: application/javascript` as it should automatically execute everything on the current page. Remember that it's a regular request and not ajax. Or am I missing something? – jgauffin May 28 '14 at 08:43
  • @jgauffin: That's why I rolled back the edit. I forgot it's not an AJAX request :(. Setting the `Content-Type` to JavaScript isn't enough. The request *has* to be loaded via a `` tag for that to work. – Matt May 28 '14 at 08:43
  • guess I remember incorrectly then :( Thanks for the clarification – jgauffin May 28 '14 at 08:46