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.

有帮助吗?

解决方案

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top