In this article, we'll be looking at how we can monetize video and audio on the web using webmonetization. Our site will be monetized only when the user is playing media content as we'll not want our user to pay for content they're not engaging with.
First, let us create a basic HTML page with video and audio.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Monetize Audio and Video</title>
</head>
<body>
<main>
<p id="state"></p>
<video class="mediaEl" src="files/videoplayback.mp4" controls></video>
<br>
<audio class="mediaEl" src="files/videoplayback.mp4" controls></audio>
</main>
We'll check if monetization is supported by the browser.
if (!document.monetization) {
const state = document.getElementById('state')
state.innerText = 'monetization not enabled in browser';
state.style.color = 'red';
}
Next, we'll add monetization eventlisteners to show the current monetization state.
function showMonetizationState() {
document.getElementById('state').innerText = document.monetization.state;
}
if (document.monetization) {
document.monetization.addEventListener(
"monetizationstop",
showMonetizationState
);
document.monetization.addEventListener(
"monetizationstart",
showMonetizationState
);
document.monetization.addEventListener(
"monetizationpending",
showMonetizationState
);
document.monetization.addEventListener(
'monetizationprogress',
showMonetizationState
);
}
Then, we'll create two functions to add and remove the monetization meta tag, these functions will be responsible for starting and stopping monetization.
// add meta
function addMonitizationMetaTag() {
// check if monetization meta tag is already set
if (document.querySelector('meta[name="monetization"]')) return;
monetizationTag = document.createElement('meta');
monetizationTag.name = 'monetization';
monetizationTag.content = 'your_payment_pointer'
document.head.appendChild(monetizationTag);
}
// remove meta
function removeMonitizationMetaTag() {
const meta = document.querySelector('meta[name="monetization"]');
meta.remove();
}
Finally, we'll get our media elements and attach event listeners to start monetization when media is playing and stop monetization when it stops or is loading content.
const mediaEl = document.querySelectorAll('.mediaEl');
mediaEl.forEach(el => {
el.addEventListener('play', addMonitizationMetaTag);
el.addEventListener('playing', addMonitizationMetaTag);
el.addEventListener('waiting', removeMonitizationMetaTag);
el.addEventListener('pause', removeMonitizationMetaTag);
});
Testing
To test our app ensure you install the coil browser extension, you'll see a green dollar badge on the coil icon to indicate when we're making payments.
Top comments (0)