Quick fix the UNSAFE_VAR_ASSIGNMENT warning in JavaScript

The UNSAFE_VAR_ASSIGNMENT “Unsafe assignment to innerHTML” is a Mozilla Linter warning for WebExtensions written in JavaScript. It can appear either from the use of their web-ext analyst tool or during a submission of a WebExtension to the Mozilla add-on site.

The UNSAFE_VAR_ASSIGNMENT description states “Due to both security and performance concerns, this may not be set using dynamic values which have not been adequately sanitized. This can lead to security issues or fairly serious performance degradation.

This warning crops up after creating text which contains HTML markup and setting an Element.innerHTML property to use that mixed string.

const hello = `<h1>​Hello world</h1>`
const body = document.getElementByTagName(`body`)
body.innerHTML = hello

A simple fix would be to do the following.

const hello = `<h1>​Hello world</h1>`
const body = document.getElementByTagName(`body`)

const parser = new DOMParser()
const parsed = parser.parseFromString(hello, `text/html`)
const tag = parsed.getElementsByTagName(`body`)[0]

body.innerHTML = ``

The DOMParser() Web API is available in Firefox, Chrome and Edge. Using its parseFromString(string, 'text/html') method, we can convert any mixed strings into an HTMLDocument and use it with other Node elements.

In a perfect world, you would separate the HTML elements and text content using document.createElement() and Node.textContext. But in my case, my WebExtension RetrotTxt uses Regular Expression replacements to reformat large bodies of text into markup. So rewriting the codebase to use the Node interface would require too much refactoring and this was an acceptable workaround.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s