Skip to content
mt-v-safe-html
GitHub

createSafeHtml

createSafeHtml return a vue plugin, it will inject global method $safeHtml.

Options

KeyTypeDefaultDescription
defaultStringstringAlthrough DOMPurify can fix some tag error, but sometimes we want prevent tag error to render unexpected result, If the sanitized tag does not match the original HTML, you can choose to display the default string
sanitizeConfigSanitizeConfigDOMPurify.sanitize ’s config
type Options = {
  defaultString?: string
  sanitizeConfig?: SanitizeConfig
}

Example for defaultString

// main.ts
import { createApp } from 'vue'
import { createSafeHtml } from 'mt-v-safe-html'

import App from './App.vue'

createApp(App)
  .use(createSafeHtml, {
    defaultString: 'Content is updating..., try again later'
  })
  .mount('#app')
<template>
  <div v-html="$safeHtml('<div>something</div></div>')"></div>
</template>

info

✨ Render result will be our defaultString, because original tag is 3, sanitized’s tag is 2 (not matched).

Example for sanitizeConfig

Just use like DOMPurify

// main.ts
import { createApp } from 'vue'
import { createSafeHtml } from 'mt-v-safe-html'
import App from './App.vue'

createApp(App)
  .use(createSafeHtml, {
    sanitizeConfig: { ADD_ATTR: ['target'] }
  })
  .mount('#app')
<template>
  <div v-html="$safeHtml(linkHtmlString)"></div>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  const linkHtmlString = ref(
    `
    <a href="https://github.com/motea927/mt-v-safe-html" target="_blank" rel="noopener noreferrer">
      link
    </a>
  `
  )
</script>

info

✨ If you don’t use sanitizeConfig, the target="_blank" will be sanitized.