DEV Community

Robert
Robert

Posted on • Edited on

Web Monetization in Vue ⚡

There is an awesome post for getting started with web monetization in React and was inspired to recreate it with Vue 3.

We're going to use a no-bundle dev server for Vue 3 called vite which allows us to develop Vue apps with Single-File Components without any bundling during development.

Create a vite app

Open up your terminal and do the following:

$ npx create-vite-app <project-name>
$ cd <project-name>
$ npm install
$ npm run dev
Enter fullscreen mode Exit fullscreen mode

Creating a hook to see if a user is web monetized

In the root of your project folder, create a file named use-web-monetization.js and paste the code below.

import { ref, onMounted } from "vue";

export const useWebMonetization = () => {
  const isMonetized = ref(false);
  const isLoading = ref(true);

  onMounted(() => {
    if (!document.monetization) {
      // No web monetization polyfill is installed (e.g. Coil).
      isLoading.value = false;
      isMonetized.value = false;
      return;
    }

    // Check the value of document.monetization.state
    // to see if a user is web monetized.
    const { state } = document.monetization;

    if (state === "stopped") {
      // Not currently sending micropayments, nor trying to.
      isLoading.value = false;
      isMonetized.value = false;
    }

    // Determine when Web Monetization has started actively paying
    document.monetization.addEventListener("monetizationstart", (event) => {
      isLoading.value = false;
      isMonetized.value = true;
    });
  });

  return {
    isMonetized,
    isLoading,
  };
}
Enter fullscreen mode Exit fullscreen mode

We created a file that has a reusable hook named useWebMonetization that returns isMonetized and isLoading states.

And now we can use it inside any .vue file like below.

<template>
    <div>
      <div v-if="isLoading">
        Loading...
      </div>
      <div v-else-if="isMonetized">
        Some exclusive content!
      </div>
      <div v-else>
        Show ads here!
      </div>
    </div>
</template>

<script>
import { useWebMonetization } from "./use-web-monetization";

export default {
  setup() {
    const { isLoading, isMonetized } = useWebMonetization();

    return {
      isLoading,
      isMonetized,
    };
  }
};
</script>
Enter fullscreen mode Exit fullscreen mode

Testing Web Monetization

test-web-monetization is a website that provides a bookmarklet that we can use to test our projects without signing up for a Coil account.

Sample App

Here's a sample simulator app to get you started.

demo

Good luck to everyone who's joining the #gftwhackathon!

Top comments (0)