I recognized that based on a context in which I want to use some parameters, there are at least 4 kinds of encoding that are necessary to avoid corrupted code being executed :
Javascript encoding when constructing a javascript code, e.g.
var a = "what's up ?" var b = "alert('" + a + "');" eval(b); // or anything else that executes b as code
URL encoding when using a string as a parameter into the url, e.g.
var a = "Bonnie & Clyde"; var b = "mypage.html?par=" + a; window.location.href = b; // or anything else that tries to use b as URL
HTML encoding when using a string as an HTML source of some element, e.g.
var a = "<script>alert('hi');</script>"; b.innerHTML = a; // or anything else that interprets a directly
HTML attribute encoding when using a string as a value of an attribute, e.g.
var a = 'alert("hello")'; var b = '<img onclick="' + a + '" />'; // or anything else that uses a as a (part of) a tag's attribute
While in the ASP.NET codebehind I'm aware of ways to encode the string in all 4 cases (using e.g. DataContractJsonSerializer
, HttpUtility.UrlEncode
, HttpUtility.HtmlEncode
and HttpUtility.HtmlAttributeEncode
), it would be quite interesting to know whether there are some utilities that I could use directly from javascript to encode / decode strings in these 4 cases.