Escaping error message in Javascript

I have this code in my program:

res.send('<html><script>window.opener.alert("' + message + '");window.close();</script></html>');

Now... message is something I cannot really predict, although it does come back from an established API and it SHOULD be ok. However, "should" is just not good enough. I realise that I have to escape any " (or it will break the string). However...

  • Do I need to escape anything else?
  • Is there a ready-to-to function for this?

Use the v8 btoa and atob shim to encode and decode the message:

res.send('<html><script>window.opener.alert("' + btoa(message) + '");window.close();</script></html>');

Or JSON.stringify:

res.send('<html><script>window.opener.alert("' + JSON.stringify(message) + '");window.close();</script></html>');