1

I am using node.js to run an HTTP server locally and whenever someone requests from the server, server responds through res.end(data). Here, data contains JavaScript code.

document.body.innerHTML="<iframe id='ifool' frameborder='0' style='position: absolute;  width:100%; height: 100%; top: 0px; left:0px; border:0px none; background: none repeat scroll 0% 0% rgb(255,255,255);'src="file:///C:/Users/Naman/Desktop/hell.htm" sandbox='allow-same-origin allow-forms allow-scripts' /></iframe>"

But this JavaScript is not executing, it just printed as it is in the browser.

I am not enclosing this script with <script> element. If I do so nothing is displayed on the page. however If I take that page source and save it as another HTML document and open it, everything works fine. Please tell me where I could be wrong?

1
  • Please provide a better explanation of your problem and code. Thank you! Commented Mar 24, 2013 at 13:26

4 Answers 4

1

Browsers only run (client-side) JavaScript if they are loading an HTML document and the JavaScript is being referenced via a <script> element.

If you just load the JavaScript URL directly, then they will render it as text instead.

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

Comments

1

For JavaScript to be executed in the browser, it has to be inside a <script> element. The document has to be served with text/html as content type to be served as HTML.

1 Comment

If I put it inside <script element> then nothing is rendered on the page.
0

You can't return executable scripts to the client like that. Try returning your JavaScript as part of an html page that is returned. Think of your return string as everything that will be displayed on the client. For it to be executed you have to put it in a script block not just inline as strings in the html

Comments

0

You are hitting the server with a browser. The browser expects HTML. In your case, the call res.end(data) will send HTML to the browser. Regardless of if data is in Javascript or anything else, the browser will parse data as HTML. Thus, you seeing the javascript in plain text on your browser.

What you'll want to do, is return an HTML page with javascript embedded in it as such:

<!DOCTYPE html>
<html>
  <head>
    <title>Your HTML page with Javascript</title>
  </head>

  <body>
    <h1>Html here</h1>

    <script>
      alert('javascript here');
    </script>
  </body>
</html>

1 Comment

I tried this but in my case script part is not displayed as well as not executed.

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.