[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79NMH3XMSJ4W4HA3VDM1DG2":3,"skill-same:01M79NMH3XMSJ4W4HA3VDM1DG2":43},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M79NMH3XMSJ4W4HA3VDM1DG2","dom-based-xss-prevention-cheat-sheet",null,"JunMystery\u002FAgent-Guidance","JunMystery","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F161468934?v=4","01M79MTMV8F0BY8NK1A92RA8A0","Jun","01M79MTMWCFBKPHN5B25E6V20B",0,"MIT","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fdom-based-xss-prevention-cheat-sheet\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# DOM based XSS Prevention Cheat Sheet\n\n## Introduction\n\nCommonly discussed, overlapping categories of [XSS (Cross-Site Scripting)](https:\u002F\u002Fowasp.org\u002Fwww-community\u002Fattacks\u002Fxss\u002F) include:\n\n- [Reflected or Stored](https:\u002F\u002Fowasp.org\u002Fwww-community\u002Fattacks\u002Fxss\u002F#stored-and-reflected-xss-attacks)\n- [DOM Based XSS](https:\u002F\u002Fowasp.org\u002Fwww-community\u002Fattacks\u002FDOM_Based_XSS).\n\nThe [XSS Prevention Cheatsheet](Cross_Site_Scripting_Prevention_Cheat_Sheet.md) does an excellent job of addressing Reflected and Stored XSS. This cheatsheet addresses DOM (Document Object Model) based XSS and is an extension (and assumes comprehension) of the [XSS Prevention Cheatsheet](Cross_Site_Scripting_Prevention_Cheat_Sheet.md).\n\nStored and reflected describe how an attack payload reaches a victim; server-side and client-side describe where untrusted data is handled unsafely. [Both stored and reflected XSS can occur on the client or server](https:\u002F\u002Fcommunity.owasp.org\u002FTypes_of_Cross-Site_Scripting#types-of-cross-site-scripting), including stored and reflected DOM-based XSS.\n\nFor server-side XSS, the server inserts untrusted data into a response without making it safe for its output context. DOM-based XSS arises from unsafe client-side processing. In either case, the injected script executes in the browser; choose controls for the actual data flow and output context.\n\nWhen a browser is rendering HTML and any other associated content like CSS or JavaScript, it identifies various rendering contexts for the different kinds of input and follows different rules for each context. A rendering context is associated with the parsing of HTML tags and their attributes.\n\n- The HTML parser of the rendering context dictates how data is presented and laid out on the page and can be further broken down into the standard contexts of HTML, HTML attribute, URL, and CSS.\n- The JavaScript or VBScript parser of an execution context is associated with the parsing and execution of script code. Each parser has distinct and separate semantics in the way they can possibly execute script code which make creating consistent rules for mitigating vulnerabilities in various contexts difficult. The complication is compounded by the differing meanings and treatment of encoded values within each subcontext (HTML, HTML attribute, URL, and CSS) within the execution context.\n\nFor the purposes of this article, we refer to the HTML, HTML attribute, URL, and CSS contexts as subcontexts because each of these contexts can be reached and set within a JavaScript execution context.\n\nIn JavaScript code, the main context is JavaScript but with the right tags and context closing characters, an attacker can try to attack the other 4 contexts using equivalent JavaScript DOM methods.\n\nThe following is an example vulnerability which occurs in the JavaScript context and HTML subcontext:\n\n```html\n \u003Cscript>\n var x = '\u003C%= taintedVar %>';\n var d = document.createElement('div');\n d.innerHTML = x;\n document.body.appendChild(d);\n \u003C\u002Fscript>\n```\n\nLet's look at the individual subcontexts of the execution context in turn.\n\n## RULE \\#1 - HTML Escape then JavaScript Escape Before Inserting Untrusted Data into HTML Subcontext within the Execution Context\n\nThere are several methods and attributes which can be used to directly render HTML content within JavaScript. These methods constitute the HTML Subcontext within the Execution Context. If these methods are provided with untrusted input, then an XSS vulnerability could result. For example:\n\n### Example Dangerous HTML Methods\n\n#### Attributes\n\n```javascript\n element.innerHTML = \"\u003CHTML> Tags and markup\";\n element.outerHTML = \"\u003CHTML> Tags and markup\";\n```\n\n#### Methods\n\n```javascript\n document.write(\"\u003CHTML> Tags and markup\");\n document.writeln(\"\u003CHTML> Tags and markup\");\n```\n\n### Guideline\n\nTo make dynamic updates to HTML in the DOM safe, we recommend:\n\n 1. HTML encoding, and then\n 2. JavaScript encoding all untrusted input, as shown in these examples:\n\n```javascript\n var ESAPI = require('node-esapi');\n element.innerHTML = \"\u003C%=ESAPI.encoder().encodeForJavascript(ESAPI.encoder().encodeForHTML(untrustedData))%>\";\n element.outerHTML = \"\u003C%=ESAPI.encoder().encodeForJavascript(ESAPI.encoder().encodeForHTML(untrustedData))%>\";\n```\n\n```javascript\n var ESAPI = require('node-esapi');\n document.write(\"\u003C%=ESAPI.encoder().encodeForJavascript(ESAPI.encoder().encodeForHTML(untrustedData))%>\");\n document.writeln(\"\u003C%=ESAPI.encoder().encodeForJavascript(ESAPI.encoder().encodeForHTML(untrustedData))%>\");\n```\n\n## RULE \\#2 - JavaScript Escape Before Inserting Untrusted Data into HTML Attribute Subcontext within the Execution Context\n\nThe HTML attribute *subcontext* within the *execution* context is divergent from the standard encoding rules. This is because the rule to HTML attribute encode in an HTML attribute rendering context is necessary in order to mitigate attacks which try to exit out of an HTML attributes or try to add additional attributes which could lead to XSS.\n\nWhen you are in a DOM execution context you only need to JavaScript encode HTML attributes which do not execute code (attributes other than event handler, CSS, and URL attributes).\n\nFor example, the general rule is to HTML Attribute encode untrusted data (data from the database, HTTP request, user, back-end system, etc.) placed in an HTML Attribute. This is the appropriate step to take when outputting data in a rendering context, however using HTML Attribute encoding in an execution context will break the application display of data.\n\n### SAFE but BROKEN example\n\n```javascript\n var ESAPI = require('node-esapi');\n var x = document.createElement(\"input\");\n x.setAttribute(\"name\", \"company_name\");\n \u002F\u002F In the following line of code, companyName represents untrusted user input\n \u002F\u002F The ESAPI.encoder().encodeForHTMLAttribute() is unnecessary and causes double-encoding\n x.setAttribute(\"value\", '\u003C%=ESAPI.encoder().encodeForJavascript(ESAPI.encoder().encodeForHTMLAttribute(companyName))%>');\n var form1 = document.forms[0];\n form1.appendChild(x);\n```\n\nThe problem is that if companyName had the value \"Johnson & Johnson\". What would be displayed in the input text field would be \"Johnson &#x26;amp; Johnson\". The appropriate encoding to use in the above case would be only JavaScript encoding to disallow an attacker from closing out the single quotes and in-lining code, or escaping to HTML and opening a new script tag.\n\n### SAFE and FUNCTIONALLY CORRECT example\n\n```javascript\n var ESAPI = require('node-esapi');\n var x = document.createElement(\"input\");\n x.setAttribute(\"name\", \"company_name\");\n x.setAttribute(\"value\", '\u003C%=ESAPI.encoder().encodeForJavascript(companyName)%>');\n var form1 = document.forms[0];\n form1.appendChild(x);\n```\n\nIt is important to note that when setting an HTML attribute which does not execute code, the value is set directly within the object attribute of the HTML element so there is no concerns with injecting up.\n\n## RULE \\#3 - Be Careful when Inserting Untrusted Data into the Event Handler and JavaScript code Subcontexts within an Execution Context\n\nPutting dynamic data within JavaScript code is especially dangerous because JavaScript encoding has different semantics for JavaScript encoded data when compared to other encodings. In many cases, JavaScript encoding does not stop attacks within an execution context. For example, a JavaScript encoded string will execute even though it is JavaScript encoded.\n\nTherefore, the primary recommendation is to **avoid including untrusted data in this context**. If you must, the following examples describe some approaches that do and do not work.\n\n```javascript\nvar x = document.createElement(\"a\");\nx.href=\"#\";\n\u002F\u002F In the line of code below, the encoded data on the right (the second argument to setAttribute)\n\u002F\u002F is an example of untrusted data that was properly JavaScript encoded but still executes.\nx.setAttribute(\"onclick\", \"\\u0061\\u006c\\u0065\\u0072\\u0074\\u0028\\u0032\\u0032\\u0029\");\nvar y = document.createTextNode(\"Click To Test\");\nx.appendChild(y);\ndocument.body.appendChild(x);\n```\n\nThe `setAttribute(name_string,value_string)` method is dangerous because it implicitly coerces the *value_string* into the DOM attribute datatype of *name_string*.\n\nIn the case above, the attribute name is an JavaScript event handler, so the attribute value is implicitly converted to JavaScript code and evaluated. In the case above, JavaScript encoding does not mitigate against DOM based XSS.\n\nOther JavaScript methods that interpret strings as code, such as `setTimeout`, `setInterval`, and `Function`, have the same risk. HTML event-handler attributes also contain [JavaScript function bodies](https:\u002F\u002Fhtml.spec.whatwg.org\u002Fmultipage\u002Fwebappapis.html#event-handler-content-attributes). Escaping every character in one payload may produce a syntax error, but JavaScript encoding is not a defense for this context: escaped identifiers remain executable when the surrounding syntax is valid.\n\n```html\n\u003C!-- Executes alert(1) when clicked; encoding the identifier does not make it safe. -->\n\u003Ca id=\"bb\" href=\"#\" onclick=\"\\u0061\\u006c\\u0065\\u0072\\u0074(1)\">Test Me\u003C\u002Fa>\n```\n\nSetting the JavaScript `onclick` property is different from setting an HTML attribute. It expects a callback; assigning a primitive string [sets it to null](https:\u002F\u002Fwebidl.spec.whatwg.org\u002F#LegacyTreatNonObjectAsNull), whether or not the string is encoded. This is type conversion, not a benefit of JavaScript encoding. Assign a trusted function, and keep untrusted values as data inside that function rather than compiling them as code.\n\n```html\n\u003Ca id=\"bb\" href=\"#\">Test Me\u003C\u002Fa>\n```\n\n```javascript\n\u002F\u002F Neither string becomes a handler.\ndocument.getElementById(\"bb\").onclick = \"alert(7)\";\ndocument.getElementById(\"bb\").onclick = \"\\u0061\\u006c\\u0065\\u0072\\u0074\\u0028\\u0037\\u0029\";\n\n\u002F\u002F A trusted function is a handler.\ndocument.getElementById(\"bb\").onclick = function () {\n    alert(\"I was called.\");\n};\n```\n\nThere are other places in JavaScript where JavaScript encoding is accepted as valid executable code.\n\n```javascript\n for(var \\u0062=0; \\u0062 \u003C 10; \\u0062++){\n     \\u0064\\u006f\\u0063\\u0075\\u006d\\u0065\\u006e\\u0074\n     .\\u0077\\u0072\\u0069\\u0074\\u0065\\u006c\\u006e\n     (\"\\u0048\\u0065\\u006c\\u006c\\u006f\\u0020\\u0057\\u006f\\u0072\\u006c\\u0064\");\n }\n \\u0077\\u0069\\u006e\\u0064\\u006f\\u0077\n .\\u0065\\u0076\\u0061\\u006c\n \\u0064\\u006f\\u0063\\u0075\\u006d\\u0065\\u006e\\u0074\n .\\u0077\\u0072\\u0069\\u0074\\u0065(111111111);\n```\n\nor\n\n```javascript\n var s = \"\\u0065\\u0076\\u0061\\u006c\";\n var t = \"\\u0061\\u006c\\u0065\\u0072\\u0074\\u0028\\u0031\\u0031\\u0029\";\n window[s](t);\n```\n\nBecause JavaScript is based on an international standard (ECMAScript), JavaScript encoding enables the support of international characters in programming constructs and variables in addition to alternate string representations (string escapes).\n\nHowever the opposite is the case with HTML encoding. HTML tag elements are well defined and do not support alternate representations of the same tag. So HTML encoding cannot be used to allow the developer to have alternate representations of the `\u003Ca>` tag for example.\n\n### HTML Encoding's Disarming Nature\n\nIn general, HTML encoding serves to castrate HTML tags which are placed in HTML and HTML attribute contexts. Working example (no HTML encoding):\n\n```html\n\u003Ca href=\"...\" >\n```\n\nNormally encoded example (Does Not Work – DNW):\n\n```html\n&#x3c;a href=... &#x3e;\n```\n\nHTML encoded example to highlight a fundamental difference with JavaScript encoded values (DNW):\n\n```html\n\u003C&#x61; href=...>\n```\n\nIf HTML encoding followed the same semantics as JavaScript encoding, the line above could have possibly worked to render a link. This difference makes JavaScript encoding a less viable weapon in our fight against XSS.\n\n## RULE \\#4 - JavaScript Escape Before Inserting Untrusted Data into the CSS Attribute Subcontext within the Execution Context\n\nNormally executing JavaScript from a CSS context required either passing `javascript:attackCode()` to the CSS `url()` method or invoking the CSS `expression()` method passing JavaScript code to be directly executed.\n\nFrom my experience, calling the `expression()` function from an execution context (JavaScript) has been disabled. In order to mitigate against the CSS `url()` method, ensure that you are URL encoding the data passed to the CSS `url()` method.\n\n```javascript\nvar ESAPI = require('node-esapi');\ndocument.body.style.backgroundImage = \"url(\u003C%=ESAPI.encoder().encodeForJavascript(ESAPI.encoder().encodeForURL(companyName))%>)\";\n```\n\n## RULE \\#5 - URL Escape then JavaScript Escape Before Inserting Untrusted Data into URL Attribute Subcontext within the Execution Context\n\nThe logic which parses URLs in both execution and rendering contexts looks to be the same. Therefore there is little change in the encoding rules for URL attributes in an execution (DOM) context.\n\n```javascript\nvar ESAPI = require('node-esapi');\nvar x = document.createElement(\"a\");\nx.setAttribute(\"href\", '\u003C%=ESAPI.encoder().encodeForJavascript(ESAPI.encoder().encodeForURL(userRelativePath))%>');\nvar y = document.createTextElement(\"Click Me To Test\");\nx.appendChild(y);\ndocument.body.appendChild(x);\n```\n\nIf you utilize fully qualified URLs then this will break the links as the colon in the protocol identifier (`http:` or `javascript:`) will be URL encoded preventing the `http` and `javascript` protocols from being invoked.\n\n## RULE \\#6 - Populate the DOM using safe JavaScript functions or properties\n\nThe most fundamental safe way to populate the DOM with untrusted data is to use the safe assignment property `textContent`.\n\nHere is an example of safe usage.\n\n```html\n\u003Cscript>\nelement.textContent = untrustedData;  \u002F\u002Fdoes not execute code\n\u003C\u002Fscript>\n```\n\n## RULE \\#7 - Fixing DOM Cross-site Scripting Vulnerabilities\n\nThe best way to fix DOM based cross-site scripting is to use the right output method (sink). For example if you want to use user input to write in a `div tag` element don't use `innerHtml`, instead use `innerText` or `textContent`. This will solve the problem, and it is the right way to re-mediate DOM based XSS vulnerabilities.\n\n**It is always a bad idea to use a user-controlled input in dangerous sources such as eval. 99% of the time it is an indication of bad or lazy programming practice, so simply don't do it instead of trying to sanitize the input.**\n\nFinally, to fix the problem in our initial code, instead of trying to encode the output correctly which is a hassle and can easily go wrong we would simply use `element.textContent` to write it in a content like this:\n\n```html\n\u003Cb>Current URL:\u003C\u002Fb> \u003Cspan id=\"contentholder\">\u003C\u002Fspan>\n...\n\u003Cscript>\ndocument.getElementById(\"contentholder\").textContent = document.baseURI;\n\u003C\u002Fscript>\n```\n\nIt does the same thing but this time it is not vulnerable to DOM based cross-site scripting vulnerabilities.\n\n## Guidelines for Developing Secure Applications Utilizing JavaScript\n\nDOM based XSS is extremely difficult to mitigate against because of its large attack surface and lack of standardization across browsers.\n\nThe guidelines below are an attempt to provide guidelines for developers when developing Web based JavaScript applications (Web 2.0) such that they can avoid XSS.\n\n### GUIDELINE \\#1 - Untrusted data should only be treated as displayable text\n\nAvoid treating untrusted data as code or markup within JavaScript code.\n\n### GUIDELINE \\#2 - Always JavaScript encode and delimit untrusted data as quoted strings when entering the application when building templated JavaScript\n\nAlways JavaScript encode and delimit untrusted data as quoted strings when entering the application as illustrated in the following example.\n\n```javascript\nvar x = \"\u003C%= Encode.forJavaScript(untrustedData) %>\";\n```\n\n### GUIDELINE \\#3 - Use document.createElement(\"...\"), element.setAttribute(\"...\",\"value\"), element.appendChild(...) and similar to build dynamic interfaces\n\n`document.createElement(\"...\")`, `element.setAttribute(\"...\",\"value\")`, `element.appendChild(...)` and similar are safe ways to build dynamic interfaces.\n\nPlease note, `element.setAttribute` is only safe for a limited number of attributes.\n\nDangerous attributes include any attribute that is a command execution context, such as `onclick` or `onblur`.\n\nExamples of safe attributes includes: `align`, `alink`, `alt`, `bgcolor`, `border`, `cellpadding`, `cellspacing`, `class`, `color`, `cols`, `colspan`, `coords`, `dir`, `face`, `height`, `hspace`, `ismap`, `lang`, `marginheight`, `marginwidth`, `multiple`, `nohref`, `noresize`, `noshade`, `nowrap`, `ref`, `rel`, `rev`, `rows`, `rowspan`, `scrolling`, `shape`, `span`, `summary`, `tabindex`, `title`, `usemap`, `valign`, `value`, `vlink`, `vspace`, `width`.\n\n### GUIDELINE \\#4 - Avoid sending untrusted data into HTML rendering methods\n\nAvoid populating the following methods with untrusted data.\n\n1. `element.innerHTML = \"...\";`\n2. `element.outerHTML = \"...\";`\n3. `document.write(...);`\n4. `document.writeln(...);`\n\n### GUIDELINE \\#5 - Avoid the numerous methods which implicitly eval() data passed to it\n\nThere are numerous methods which implicitly `eval()` data passed to it that must be avoided.\n\nMake sure that any untrusted data passed to these methods is:\n\n1. Delimited with string delimiters\n2. Enclosed within a closure or JavaScript encoded to N-levels based on usage\n3. Wrapped in a custom function.\n\nEnsure to follow step 3 above to make sure that the untrusted data is not sent to dangerous methods within the custom function or handle it by adding an extra layer of encoding.\n\n#### Utilizing an Enclosure (as suggested by Gaz)\n\nThe example that follows illustrates using closures to avoid double JavaScript encoding.\n\n```javascript\n var ESAPI = require('node-esapi');\n setTimeout((function(param) { return function() {\n          customFunction(param);\n        }\n })(\"\u003C%=ESAPI.encoder().encodeForJavascript(untrustedData)%>\"), y);\n```\n\nThe other alternative is using N-levels of encoding.\n\n#### N-Levels of Encoding\n\nIf your code looked like the following, you would need to only double JavaScript encode input data.\n\n```javascript\nsetTimeout(\"customFunction('\u003C%=doubleJavaScriptEncodedData%>', y)\");\nfunction customFunction (firstName, lastName)\n     alert(\"Hello\" + firstName + \" \" + lastName);\n}\n```\n\nThe `doubleJavaScriptEncodedData` has its first layer of JavaScript encoding reversed (upon execution) in the single quotes.\n\nThen the implicit `eval` of `setTimeout` reverses another layer of JavaScript encoding to pass the correct value to `customFunction`\n\nThe reason why you only need to double JavaScript encode is that the `customFunction` function did not itself pass the input to another method which implicitly or explicitly called `eval` If *firstName* was passed to another JavaScript method which implicitly or explicitly called `eval()` then `\u003C%=doubleJavaScriptEncodedData%>` above would need to be changed to `\u003C%=tripleJavaScriptEncodedData%>`.\n\nAn important implementation note is that if the JavaScript code tries to utilize the double or triple encoded data in string comparisons, the value may be interpreted as different values based on the number of `evals()` the data has passed through before being passed to the if comparison and the number of times the value was JavaScript encoded.\n\nIf **A** is double JavaScript encoded then the following **if** check will return false.\n\n``` javascript\n var x = \"doubleJavaScriptEncodedA\";  \u002F\u002F\\u005c\\u0075\\u0030\\u0030\\u0034\\u0031\n if (x == \"A\") {\n    alert(\"x is A\");\n } else if (x == \"\\u0041\") {\n    alert(\"This is what pops\");\n }\n```\n\nThis brings up an interesting design point. Ideally, the correct way to apply encoding and avoid the problem stated above is to server-side encode for the output context where data is introduced into the application.\n\nThen client-side encode (using a JavaScript encoding library such as [node-esapi](https:\u002F\u002Fgithub.com\u002FESAPI\u002Fnode-esapi\u002F)) for the individual subcontext (DOM methods) which untrusted data is passed to.\n\nHere are some examples of how they are used:\n\n```javascript\n\u002F\u002Fserver-side encoding\nvar ESAPI = require('node-esapi');\nvar input = \"\u003C%=ESAPI.encoder().encodeForJavascript(untrustedData)%>\";\n```\n\n```javascript\n\u002F\u002FHTML encoding is happening in JavaScript\nvar ESAPI = require('node-esapi');\ndocument.writeln(ESAPI.encoder().encodeForHTML(input));\n```\n\nOne option is utilize ECMAScript 5 immutable properties in the JavaScript library.\nAnother option provided by Gaz (Gareth) was to use a specific code construct to limit mutability with anonymous closures.\n\nAn example follows:\n\n```javascript\nfunction escapeHTML(str) {\n     str = str + \"''\";\n     var out = \"''\";\n     for(var i=0; i\u003Cstr.length; i++) {\n         if(str[i] === '\u003C') {\n             out += '&lt;';\n         } else if(str[i] === '>') {\n             out += '&gt;';\n         } else if(str[i] === \"'\") {\n             out += '&#39;';\n         } else if(str[i] === '\"') {\n             out += '&quot;';\n         } else {\n             out += str[i];\n         }\n     }\n     return out;\n}\n```\n\n### GUIDELINE \\#6 - Use untrusted data on only the right side of an expression\n\nUse untrusted data on only the right side of an expression, especially data that looks like code and may be passed to the application (e.g., `location` and `eval()`).\n\n```javascript\nwindow[userDataOnLeftSide] = \"userDataOnRightSide\";\n```\n\nUsing untrusted user data on the left side of the expression allows an attacker to subvert internal and external attributes of the window object, whereas using user input on the right side of the expression doesn't allow direct manipulation.\n\n### GUIDELINE \\#7 - When URL encoding in DOM be aware of character set issues\n\nWhen URL encoding in DOM be aware of character set issues as the character set in JavaScript DOM is not clearly defined (Mike Samuel).\n\n### GUIDELINE \\#8 - Limit access to object properties when using object\\[x\\] accessors\n\nLimit access to object properties when using `object[x]` accessors (Mike Samuel). In other words, add a level of indirection between untrusted input and specified object properties.\n\nHere is an example of the problem using map types:\n\n```javascript\nvar myMapType = {};\nmyMapType[\u003C%=untrustedData%>] = \"moreUntrustedData\";\n```\n\nThe developer writing the code above was trying to add additional keyed elements to the `myMapType` object. However, this could be used by an attacker to subvert internal and external attributes of the `myMapType` object.\n\nA better approach would be to use the following:\n\n```javascript\nif (untrustedData === 'location') {\n  myMapType.location = \"moreUntrustedData\";\n}\n```\n\n### GUIDELINE \\#9 - Keep HTML sanitization separate from JavaScript execution\n\nUse an HTML sanitizer such as [DOMPurify](https:\u002F\u002Fgithub.com\u002Fcure53\u002FDOMPurify#what-does-it-do) when the application must render untrusted markup; see the [HTML sanitization guidance](Cross_Site_Scripting_Prevention_Cheat_Sheet.md#html-sanitization). HTML sanitizers filter markup and do not provide a sandbox for executing arbitrary JavaScript. Do not pass untrusted code to [`eval()` or `Function()`](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FJavaScript\u002FReference\u002FGlobal_Objects\u002Feval#never_use_direct_eval!).\n\n### GUIDELINE \\#10 - Don't eval() JSON to convert it to native JavaScript objects\n\nDon't `eval()` JSON to convert it to native JavaScript objects. Use the built-in `JSON.parse()` to deserialize JSON into JavaScript values, and `JSON.stringify()` to serialize JavaScript values into JSON. `JSON.parse()` rejects anything that is not valid JSON, so it cannot execute attacker-supplied code the way `eval()` can.\n\n> [!WARNING]\n> `JSON.stringify()` is **not** an output-encoding function. Its output is valid JSON, but embedding it in HTML requires protection for the destination context. Prefer a separate response with `Content-Type: application\u002Fjson`, parsed client-side with `JSON.parse()`. If JSON must be embedded in an inline script, use a serializer or encoder documented for that exact placement, protecting both JavaScript syntax and the [enclosing HTML script context](https:\u002F\u002Fhtml.spec.whatwg.org\u002Fmultipage\u002Fscripting.html#restrictions-for-contents-of-script-elements), including literal `\u003C\u002Fscript` sequences. HTML entity encoding or JavaScript quote escaping alone is not sufficient for this placement. For other placements, follow the [context-specific XSS encoding rules](Cross_Site_Scripting_Prevention_Cheat_Sheet.md#output-encoding).\n\n## Common Problems Associated with Mitigating DOM Based XSS\n\n### Complex Contexts\n\nIn many cases the context isn't always straightforward to discern.\n\n```html\n\u003Ca href=\"javascript:myFunction('\u003C%=untrustedData%>', 'test');\">Click Me\u003C\u002Fa>\n ...\n\u003Cscript>\nFunction myFunction (url,name) {\n    window.location = url;\n}\n\u003C\u002Fscript>\n```\n\nIn the above example, untrusted data started in the rendering URL context (`href` attribute of an `a` tag) then changed to a JavaScript execution context (`javascript:` protocol handler) which passed the untrusted data to an execution URL subcontext (`window.location` of `myFunction`).\n\nBecause the data was introduced in JavaScript code and passed to a URL subcontext the appropriate server-side encoding would be the following:\n\n```html\n\u003Ca href=\"javascript:myFunction('\u003C%=ESAPI.encoder().encodeForJavascript(ESAPI.encoder().encodeForURL(untrustedData)) %>', 'test');\">\nClick Me\u003C\u002Fa>\n ...\n```\n\nOr if you were using ECMAScript 5 with an immutable JavaScript client-side encoding libraries you could do the following:\n\n```html\n\u003C!-- server side URL encoding has been removed.  Now only JavaScript encoding on server side. -->\n\u003Ca href=\"javascript:myFunction('\u003C%=ESAPI.encoder().encodeForJavascript(untrustedData)%>', 'test');\">Click Me\u003C\u002Fa>\n ...\n\u003Cscript>\nFunction myFunction (url,name) {\n    var encodedURL = ESAPI.encoder().encodeForURL(url);  \u002F\u002FURL encoding using client-side scripts\n    window.location = encodedURL;\n}\n\u003C\u002Fscript>\n```\n\n### Inconsistencies of Encoding Libraries\n\nThere are a number of open source encoding libraries out there:\n\n1. OWASP [ESAPI](https:\u002F\u002Fowasp.org\u002Fwww-project-enterprise-security-api\u002F)\n2. OWASP [Java Encoder](https:\u002F\u002Fowasp.org\u002Fwww-project-java-encoder\u002F)\n3. Apache Commons Text [StringEscapeUtils](https:\u002F\u002Fcommons.apache.org\u002Fproper\u002Fcommons-text\u002Fjavadocs\u002Fapi-release\u002Forg\u002Fapache\u002Fcommons\u002Ftext\u002FStringEscapeUtils.html), replace one from [Apache Commons Lang3](https:\u002F\u002Fcommons.apache.org\u002Fproper\u002Fcommons-lang\u002Fapidocs\u002Forg\u002Fapache\u002Fcommons\u002Flang3\u002FStringEscapeUtils.html)\n4. [Jtidy](http:\u002F\u002Fjtidy.sourceforge.net\u002F)\n5. Your company's custom implementation.\n\nSome work on a denylist while others ignore important characters like \"&lt;\" and \"&gt;\".\n\nJava Encoder is an active project providing supports for HTML, CSS and JavaScript encoding.\n\nESAPI is one of the few which works on an allowlist and encodes all non-alphanumeric characters. It is important to use an encoding library that understands which characters can be used to exploit vulnerabilities in their respective contexts. Misconceptions abound related to the proper encoding that is required.\n\n### Encoding Misconceptions\n\nMany security training curriculums and papers advocate the blind usage of HTML encoding to resolve XSS.\n\nThis logically seems to be prudent advice as the JavaScript parser does not understand HTML encoding.\n\nHowever, if the pages returned from your web application utilize a content type of `text\u002Fxhtml` or the file type extension of `*.xhtml` then HTML encoding may not work to mitigate against XSS.\n\nFor example:\n\n```html\n\u003Cscript>\n&#x61;lert(1);\n\u003C\u002Fscript>\n```\n\nThe HTML encoded value above is still executable. If that isn't enough to keep in mind, you have to remember that encodings are lost when you retrieve them using the value attribute of a DOM element.\n\nLet's look at the sample page and script:\n\n```html\n\u003Cform name=\"myForm\" ...>\n  \u003Cinput type=\"text\" name=\"lName\" value=\"\u003C%=ESAPI.encoder().encodeForHTML(last_name)%>\">\n ...\n\u003C\u002Fform>\n\u003Cscript>\n  var x = document.myForm.lName.value;  \u002F\u002Fwhen the value is retrieved the encoding is reversed\n  document.writeln(x);  \u002F\u002Fany code passed into lName is now executable.\n\u003C\u002Fscript>\n```\n\nFinally there is the problem that certain methods in JavaScript which are usually safe can be unsafe in certain contexts.\n\n### Usually Safe Methods\n\nOne example of an attribute which is thought to be safe is `innerText`.\n\nSome papers or guides advocate its use as an alternative to `innerHTML` to mitigate against XSS in `innerHTML`. However, depending on the tag which `innerText` is applied, code can be executed.\n\n```html\n\u003Cscript>\n var tag = document.createElement(\"script\");\n tag.innerText = \"\u003C%=untrustedData%>\";  \u002F\u002Fexecutes code\n\u003C\u002Fscript>\n```\n\nThe `innerText` feature was originally introduced by Internet Explorer, and was formally specified in the HTML standard in 2016 after being adopted by all major browser vendors.\n\n### Detect DOM XSS using variant analysis\n\n**Vulnerable code:**\n\n```\n\u003Cscript>\nvar x = location.hash.split(\"#\")[1];\ndocument.write(x);\n\u003C\u002Fscript>\n```\n\nSemgrep rule to identify above dom xss [link](https:\u002F\u002Fsemgrep.dev\u002Fs\u002Fwe30).\n\n## References\n\n- [MDN: innerHTML Security Considerations](https:\u002F\u002Fdeveloper.mozilla.org\u002Fen-US\u002Fdocs\u002FWeb\u002FAPI\u002FElement\u002FinnerHTML#security_considerations)\n- [DOMPurify: HTML Sanitization](https:\u002F\u002Fgithub.com\u002Fcure53\u002FDOMPurify#what-does-it-do)\n",{},"main","5d0a87185c0e172c3901e2a6e5916b6d544b8b94","skills\u002Fdom-based-xss-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance","https:\u002F\u002Fgithub.com\u002FJunMystery","AI is the typist, I am the architect. Building efficient, secure, and user-centric products through disciplined AI prompt engineering.","2026-11-13 17:41:25",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add JunMystery\u002FAgent-Guidance --skill dom-based-xss-prevention-cheat-sheet",{"tool":35,"command":36},"bunx","bunx skills add JunMystery\u002FAgent-Guidance --skill dom-based-xss-prevention-cheat-sheet",{"tool":38,"command":39},"pnpm","pnpm dlx skills add JunMystery\u002FAgent-Guidance --skill dom-based-xss-prevention-cheat-sheet","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fdom-based-xss-prevention-cheat-sheet\u002FSKILL.md",true,[],[44,50,56,62,68,74],{"skillNo":45,"name":46,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":47,"categories":48,"keywords":49,"publishedAt":18},"01M79QR1E309VJ6CTQKB32AWWA","zero-trust-architecture-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fzero-trust-architecture-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M79QQV7GHYR02DYGN41S23WN","xss-filter-evasion-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxss-filter-evasion-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M79QQNSN7YB8XB61FFSCS3WH","xs-leaks-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxs-leaks-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M79QQHZZJKFDY9132G5A65C2","xpath-injection-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxpath-injection-prevention-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M79QQB9ZSD3DJG8658EHQXR1","xml-security-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-security-cheat-sheet\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M79QQ60WKV7PFMXWT9CW8PM6","xml-external-entity-prevention-cheat-sheet","https:\u002F\u002Fgithub.com\u002FJunMystery\u002FAgent-Guidance\u002Fblob\u002Fmain\u002Fskills\u002Fxml-external-entity-prevention-cheat-sheet\u002FSKILL.md",[],[]]