Home > Software engineering >  Insert script into HTML string
Insert script into HTML string

Time:11-24

Im running on a node server and returning the HTML for a given URL

server.get('*', async (request, response) => {
  const url = request.protocol   '://'   request.get('host')   request.originalUrl;

  const { html } = await renderPage(url, {
    manifest,
    preload: true,
    request,
    response
  });

  //TODO: Insert script into html string in head

  response.end(html);
});

However, what I would like is that I could manipulate the HTML before response.end(), eg inserting a script into the head section of the HTML string... Any ideas on how to do this?

I was thinking at first I somehow could use html.replace(), but that's not the right approach I think...

Any help would be greatly appreciated :)

CodePudding user response:

Not knowing the types but if html is just a string, the .replace() method is an appropriate way to go. Depending on if you have control over the html templates which are rendered you could add a placeholder to add the script to a certain place in the html.

If you have no control I rather would just append it to the end of the body.

const script = `<script src="your/fancy/script.js" />`;

html.replace(/(<\s*\/\s*body)/, `${scripts}\n$1`);

should put the script like

  <div>Some content before</div>
<script src="your/fancy/script.js" />
</body>
</html>
  • Related