Search code examples
node.jshttpwebservernode.js-connect

Dynamically inject script tag pre </body>


At the end of a request I would like to tap into the results that are text/html end inject </body> tag. Ideally this would tap in as low as possible - i.e. HTTP module or at worst Connect.

I'm trying to create a package that will be used for debugging and when debugging is enabled, I want the scripts to be injected. Getting this in as low as possible just means that the package I'm working on is as compatible as possible.


Solution

  • One way might be to monkey patch ServerResponse.end like so:

    var http = require('http');
    
    var oldEnd = http.ServerResponse.prototype.end,
        RE_CONTYPE_HTML = /Content-Type: text\/html/i;
    http.ServerResponse.prototype.end = function(data, encoding) {
      if (RE_CONTYPE_HTML.test(this._header)) {
        if (data)
          this.write(data, encoding);
        this.write('<script>window.onload = function(){ alert("Hello World!"); };</script>', 'ascii');
        oldEnd.call(this);
      } else
        oldEnd.call(this, data, encoding);
    };
    
    http.createServer(function(req, res) {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end('<h1>Greetings from node.js!</h1>');
    }).listen(8000);