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

4
  • The browser expects HTML... Have you tried encapsulating the script in minimal HTML, including a <body onLoad="..."> ? Commented May 28, 2014 at 8:34
  • How are you initiating the request? Commented May 28, 2014 at 8:34
  • @RoyDictus: the Content-Type controls what the browser expects. Commented May 28, 2014 at 8:37
  • @RichieHindle: I've tried both with GET and POST. Commented May 28, 2014 at 8:37

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

8 Comments

Not possible. The response is conditinal depending on the incoming data. It can either be a file or a javascript.
@jgauffin: The response can either be a file or a JavaScript? That doesn't sound very consistent...
@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: "It's not my system": Yea, that explains that :-)
@jgauffin: If my answer isn't possible, then I'm AFAIK, you're out of options.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.