changeset 7538:74ec3a3bfdc7

js: introduce an html_escape function In analogy to (python) kallithea.lib.helpers.html_escape, introduce the equivalent for use in JavaScript.
author Mads Kiilerich <mads@kiilerich.com>
date Mon, 11 Feb 2019 21:36:13 +0100
parents 9e026d2426c9
children 22da5f258118
files kallithea/public/js/base.js
diffstat 1 files changed, 24 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/kallithea/public/js/base.js	Sat Feb 23 21:10:59 2019 +0100
+++ b/kallithea/public/js/base.js	Mon Feb 11 21:36:13 2019 +0100
@@ -8,6 +8,30 @@
 }
 
 /**
+ * INJECT .html_escape function into String
+ * Usage: "unsafe string".html_escape()
+ *
+ * This is the Javascript equivalent of kallithea.lib.helpers.html_escape(). It
+ * will escape HTML characters to prevent XSS or other issues.  It should be
+ * used in all cases where Javascript code is inserting potentially unsafe data
+ * into the document.
+ *
+ * For example:
+ *      <script>confirm("boo")</script>
+ * is changed into:
+ *      &lt;script&gt;confirm(&quot;boo&quot;)&lt;/script&gt;
+ *
+ */
+String.prototype.html_escape = function() {
+    return this
+        .replace(/&/g,'&amp;')
+        .replace(/</g,'&lt;')
+        .replace(/>/g,'&gt;')
+        .replace(/"/g, '&quot;')
+        .replace(/'/g, '&#039;');
+}
+
+/**
  * INJECT .format function into String
  * Usage: "My name is {0} {1}".format("Johny","Bravo")
  * Return "My name is Johny Bravo"