Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue - style user input in confirm message (allow specific html tags)

Tags:

xss

vue.js

vuejs2

Using Vue, I want to show a confirmation modal that says something like "Are you sure you want to delete '{{itemName}}'?".

That's easy enough with a Javascript string being bound to a variable which is embedded in the template.

However, if I want to put the itemName in italics to emphasis it, the only way I can find is to use v-html, which of course would open it up to XSS.

Is there any way to style part of the string?

like image 475
Allan Jardine Avatar asked Mar 18 '19 16:03

Allan Jardine


People also ask

What is a confirmation dialogue in Vue JS?

A confirmation dialogue is a UI pattern where the user will be given a choice to continue with their action or to cancel it. It is commonly used with destructive or irreversible actions, to make sure that the user would indeed want to proceed. In this article,we'll be implementing a reusable and modular confirmation dialogue in Vue.js.

How to check if an HTML attribute is enabled or disabled?

We can check HTML attributes against the data () object values. emailEnabled is set to false, therefore, the email field is disabled. We can enable/disable other HTML attributes the same way, e.g. required.

Is⚠️ Vue native deprecated?

⚠️ Vue Native has been deprecated and is no longer maintained. To let users interact with your app, we can use the v-bind directive to attach event listeners that invoke methods on our Vue Native instances:


1 Answers

You can try to use a package like sanitize-html. Here is how I would do it:

Install:

npm install sanitize-html

main.js:

import sanitizeHTML from 'sanitize-html';
Vue.prototype.$sanitize = sanitizeHTML;

YourComponent.vue:

<div v-html="$sanitize(itemName)" />

Have a look at the README for more information about default options for allowed tags and attributes.

EDIT resp. Alternatives:

sanitize-html has a drawback of a 327 KB weight. But there are smaller packages available:

  • DOMPurify (15 KB)
  • js-xss (28 KB)

EDIT 2:

There is a package vue-dompuritfy-html which we are using in our projects now. After installing you can simply use

<div v-dompurify-html="itemName" />

Bonus: with the use of this package you cover the recommended eslint rule vue/no-v-html

like image 155
RWAM Avatar answered Jan 04 '23 13:01

RWAM