Mr.J
2 min readFeb 7, 2019

--

This is great thinking. While at the time these libraries were great, JavaScript now has native support. This allows us to still use these same techniques without the overhead and dependency of a framework that at some point will drop support.

While these frameworks do some work on preventing XSS, if you actually review the source, it’s actually just a simple encode function that turns html into HTML entities. To include a whole library because of this reason is complete absurd.

Here is my solution to this concern.

So I have used template literals by first defining a template in the HTML.

<template>
<div>
<h1>Data Display</h1>
<p>${name}</p>
<p>${date}</p>
</div>
</template>

Now when you select this in JavaScript you end up with a string instead of a template literal, which cannot be parsed by the browser engine.

const template = document.querySelector(‘template’)
const data = {name: ‘MrJ’, date: ‘10/10/2020’}
someDiv.innerHTML = template.innerHTML

Nobody really wants to add the HTML into the JS, so use this function

function interpolate(template, params) {
const replaceTags = { ‘&’: ‘&amp;’, ‘<’: ‘&lt;’, ‘>’: ‘&gt;’, ‘(‘: ‘%28’, ‘)’: ‘%29’ }
const safeInnerHTML = text => text.toString()
.replace(/[&<>\(\)]/g, tag => replaceTags[tag] || tag)
const keys = Object.keys(params)
const keyVals = Object.values(params).map(safeInnerHTML)
return new Function(…keys, `return \`${template}\``)(…keyVals)
}

Just like Mustache you get the security and templating

someDiv.innerHTML = interpolate(template.innerHTML.toString().trim(), data)

If you wanted to use tagged templates

function encode(template, ...expressions) {
const replaceTags = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '(': '%28', ')': '%29' }
const safeInnerHTML = text => text
.replace(/[&<>\(\)]/g, tag => replaceTags[tag] || tag)
return template.reduce((result, part, i) => result + safeInnerHTML(expressions[i - 1]) + part)
}
someDiv.innerHTML = encode `<div>
<h1>Data Display</h1>
<p>${name}</p>
<p>${date}</p>
</div>`

Hope this helps the article from naysayers.

--

--