在Javascript中转义错误信息
我在我的程序中有这个代码:
res.send('<html><script>window.opener.alert("' + message + '");window.close();</script></html>');
现在… message
是我不能真正预测的东西,虽然它确实从一个已build立的API中回来,它应该是可以的。 但是,“应该”还不够好。 我意识到我必须逃脱任何"
(或者它会打破string),但是…
- 我需要逃避什么吗?
- 是否有准备好的function呢?
使用v8 btoa和atob shim对消息进行编码和解码:
res.send('<html><script>window.opener.alert("' + btoa(message) + '");window.close();</script></html>');
或者JSON.stringify:
res.send('<html><script>window.opener.alert("' + JSON.stringify(message) + '");window.close();</script></html>');