js

Quick fix the UNSAFE_VAR_ASSIGNMENT warning in JavaScript

Reading time of 214 words
1 minute
Reading time of 214 words ~ 1 minute


If you find this content useful, consider buying me a coffee
Or help me out by engaging with any advertisers that you find interesting

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.

Written by Ben Garrett

If you find this content useful, consider buying me a coffee
Or help me out by engaging with any advertisers that you find interesting