11

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 Answer 1

16

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());
});
Sign up to request clarification or add additional context in comments.

5 Comments

It works! But now any other scripts already embedded in the .html aren't executed. How can I fix that? Thank you.
what do you mean they arent executed? did it remove them? was there an error? please detail
when I do console.log($.html()); I can see the scripts, eg. <script src="js/main.js"></script> in the html but they aren't triggered like the appended scriptNode. I didn't have this problem with the code I have in the description.
if you say the scripts arent running on the page when it loads, you need to be looking at the browser console to see if there are any client-side js errors
You are right I forgot to configure again express.static server. Thanks again for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.