WebExtensions

Quick fix the UNSAFE_VAR_ASSIGNMENT warning in JavaScript


Edit 29 April 2018: Updated answer with the iteration suggestion of Lee Wei.

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

becomes

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><strong style="text-decoration: underline">Hello</strong> world</h1><p>Let's iterate!</p>`
document.body.innerHTML = hello

A quick fix would be to do the following.

const hello = `​​​​<h1><strong style="text-decoration: underline">Hello</strong> world</h1><p>Let's iterate!</p>`

const parser = new DOMParser()
const parsed = parser.parseFromString(hello, `text/html`)
const tags = parsed.getElementsByTagName(`body`)

document.body.innerHTML = ``
for (const tag of tags) {
document.body.appendChild(tag)
}

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.

Advertisements

2 thoughts on “Quick fix the UNSAFE_VAR_ASSIGNMENT warning in JavaScript

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s