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 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.

If the value assigned is a simple string you can replace the element.innerHTML property with an element.textContent property.

const hello = `Hello world`
document.body.innerHTML = hello


const hello = `Hello world`
document.body.textContent = hello

But what do you do if the assigned value contains a mix of text and HTML tags for parsing?

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

A quick fix would be to do the following.

const hello = `<h1>​Hello world</h1>`

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

document.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.


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