Inject javascript code into html with Express

本秂侑毒 提交于 2021-02-07 12:21:26

问题


I am writing a web application using Express framework to generate Impress.js presentations and apply a visual editor on them. I have set up the app.js for only getting the .html file but I want to inject a javascript code from a separate file before the body closing tag of the .html file.

For example, I will have a route handler /edit and then the script will be triggered after it have been injected into the html code.

var express = require('express');

var app = express();


app.configure(function(){
    app.use(express.static(__dirname + '/public'));
});

app.get('/:file', function(req, res) {
  res.sendfile(__dirname + '/public' + file);
});

app.listen(3000);
console.log('Listening on port 3000');

Any ideas on how to achieve this would be more than welcome!


回答1:


Just an idea, but you could use something like cheerio to append a script to the body

app.get('/:file', function(req, res) {
  var html = fs.readFileSync(__dirname + '/public' + file, 'utf8');
  var $ = cheerio.load(html);
  var scriptNode = '<script>alert("script appended!");</script>';
  $('body').append(scriptNode);
  res.send($.html());
});


来源:https://stackoverflow.com/questions/15574335/inject-javascript-code-into-html-with-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!