How to write a URL cleaner using custom directives in Vue.js

32bcffc31ef630f9fcc26d45d4313a91.jpeg

Learn to make custom directives: Build safe URL sanitization directives

b398bb82e8f1a841e285925fa1a1b0f6.jpeg

Beginning

Vue.js comes with a set of default directives that are important for common use cases. These default directives include v-for, v-html, and v-text. In addition, Vue.js also gives us the ability to register custom directives to meet specific needs.

Custom directives often include lifecycle hooks and can operate on stages such as "mounted", "updated" and "beforeUnmount". These hooks receive elements of application directives and their associated values, allowing them to perform specific actions on the input.

Additionally, functions can be selectively triggered based on specific lifecycle hooks such as 'onUpdated' or 'beforeUnmount'

Review how to customize registration instructions

Instructions can be registered in three different ways. They can be registered inside a script setup (setup function) or outside a setup function (setup function), or they can be registered globally during application initialization.

1. Function internal registration

In Vue.js, variables declared with camelCase and prefixed with 'v' are automatically recognized as directives. In the above example, we defined the v-text-color directive, which accepts a bound element and sets the text color based on the provided value.

<script setup>
import { ref } from 'vue'

const msg = ref('Hello World!')

const vTextColor = {
  mounted: (el,binding) => el.style.color = binding.value
}
</script>

<template>
  <h1 v-text-color="`green`">{
    
    { msg }}</h1>
  <input v-model="msg">
</template>

2. Function external registration

We can also register directives outside of the setup function using the directives API option. The code snippet below demonstrates how to achieve this.

export default {
  setup() {
    /*...*/
  },
  directives: {
    // enables v-textcolor in template
    textcolor: {
      /* ... */
    }
  }
}

3. Global registration

For directives that you plan to reuse frequently throughout your application, it is recommended to register them globally, like this:

const app = createApp({})

// make v-textcolor usable in all components
app.directive('textcolor', {
  /* ... */
})

Create our custom URL sanitization directive

Now that we've explored the different ways to register custom directives in Vue.js, let's move on to creating a directive that safely sanitizes the provided URL. To avoid reinventing the wheel and ensure robustness of URL parsing, we will utilize the @braintree/sanitize-url package. The package has been extensively tested, has widespread adoption among developers, and is actively maintained.

Essentially, the purpose of this directive is to get the value of the bound element, which is a URL, and sanitize it to ensure its safety. Depending on your preferred package manager, you can install '@braintree/sanitize-url'. In this example we will use npm.

npm install -S @braintree/sanitize-url

Unsafe URL

Here is an example of an unsafe URL we aim to clean.

http://example.com/login?redirect=http://malicious-site.com/attack?payload=<script>alert('XSS Attack');</script>

In this example:

  • The URL appears to be a login page (http://example.com/login) with a redirected query parameter.

  • The redirect parameter points to a potentially malicious website (http://malicious-site.com/attack) and contains a payload that may perform a cross-site scripting attack (XSS).

Our custom URL cleaner

<script setup>
import { ref } from 'vue'
import { sanitizeUrl } from '@braintree/sanitize-url'

const  msg = ref('Hello World!')
const url = ref('http://example.com/login?redirect=http://malicious-site.com/attack?payload=<script>alert('XSS Attack');</script>
')

const vSafeUrl = {
  mounted:(el,binding)=> {
    el.setAttribute('href', sanitizeUrl(binding.value))
    }
}
</script>

<template>
  <h1>{
    
    { msg }}</h1>
  <a v-safe-url="`url`">Safe url</a>
</template>

Finish

Exploring custom directives in Vue.js highlights their excellent adaptability and usefulness in tailoring applications to specific needs. In this article we also looked at various directive registration methods, demonstrating Vue's flexibility in defining its scope and reusability.

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like to remind you that the creation of articles is not easy. If you like my sharing, please don’t forget to like and forward it to let more people in need See. At the same time, if you want to gain more knowledge about front-end technology, please follow me. Your support will be my biggest motivation for sharing. I will continue to output more content, so stay tuned.

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/132819915