动态注入脚本标签前</body>

问题描述 投票:0回答:1

在请求结束时,我想利用

text/html
结束注入
</body>
标签的结果。理想情况下,这将尽可能低地利用 - 即 HTTP 模块或最坏的连接。

我正在尝试创建一个用于调试的包,当启用调试时,我希望注入脚本。让它尽可能低只意味着我正在开发的包尽可能兼容。

node.js http webserver node.js-connect
1个回答
2
投票

一种方法可能是像这样猴子修补 ServerResponse.end :

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);
© www.soinside.com 2019 - 2024. All rights reserved.