简体   繁体   中英

Javascript not executing with node js module

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?

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.

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.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM