Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 707
vdh_ant Avatar asked Mar 28 '26 18:03

vdh_ant


1 Answers

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);
like image 194
mscdex Avatar answered Mar 31 '26 09:03

mscdex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!