Home > Blockchain >  Is v-html safe when outputting text?
Is v-html safe when outputting text?

Time:03-26

In laravel/blade apps I used Purifier to make making of output text safe :

{!! Purifier::clean($pageContent->content) !!} 

I wonder are there some similar tools in vuejs3, to make safe output in line like :

<div v-html="currencyDetails.description" ></div>

Seems v-html is not safe in this way. How can I s0lve it ?

CodePudding user response:

You can use sanitize-html. You can create a directive out of it.

v-sanitize-html.js

import sanitizeHtml from 'sanitize-html';

export default {
  // Vue Hook Functions
  inserted(el, binding) {
    const { value } = binding;
    const options = {
      allowedTags: [
        // Headers
        'h1',
        'h2',
        'h3',
        'h4',
        'h5',
        'h6',
        // Styles
        'b',
        'i',
        'em',
        'strong',
        's',
        'sup',
        'sub',
        // Paragraph / Line-breaks
        'p',
        'br',
        'hr',
        // Anhor
        'a',
        // Image
        'img',
        // List
        'ol',
        'ul',
        'li',
        // Blockquote
        'blockquote',
        // Table
        'table',
        'tbody',
        'caption',
        'tr',
        'th',
        'td',
        // Misc
        'div',
        'span',
      ],
      allowedAttributes: {
        h1: ['id'],
        h2: ['id'],
        h3: ['id'],
        h4: ['id'],
        h5: ['id'],
        h6: ['id'],
        p: ['style'],
        a: ['href', 'target'],
        img: ['src', 'width', 'height', 'style'],
        div: ['id', 'class', 'style'],
      },
      allowedClasses: {
        '*': ['*'],
      },
    };
    el.innerHTML = sanitizeHtml(value, options);
  },
};

and use it in any component like.

import sanitizeHtml from '@directives/v-sanitize-html';

export default {
  directives: {
    sanitizeHtml,
  },
};
<div v-sanitize-html="currencyDetails.description" ></div>
  • Related