Sometimes you don't want your entire site to be web monetized. The easiest way to partially monetize your site is to just include the Web Monetization
meta tag on specific pages. But if you want to turn Web Monetization on and off dynamically, you can do that too!
This example shows how to turn Web Monetization on and off dynamically in response to a visitor clicking a button.
#How does it work?
To display the current monetization state on the page, we bind the
three monetization state events:
monetizationstart. Each time one of them fires we display the current monetization state.
This isn't required to start and stop monetization but it helps visualize it on the example page.
When the page loads we set an initial state. If the visitor doesn't have Web Monetization (
document.monetization is not defined), we say Not enabled in browser. Otherwise, we display the current monetization state.
We need to grab the meta tag's element object in order to add and remove it. The query selector,
meta[name="monetization"], selects a
<meta> tag with a
name attribute of
monetization (the Web Monetization meta tag).
When the Stop button is clicked, we call
remove() on the monetization tag element. Your Web Monetization extension will pick up this change and stop monetization right away.
When the Start button is clicked, we append the monetization tag to the document's head. Your Web Monetization extension will pick up this change and begin initializing Web Monetization.
This example simulates turning Web Monetization on and off dynamically in response to a visitor clicking a button.
A web monetized visitor can see the monetization state and control it with the buttons. The state changes to
stopped when Stop Monetization is clicked. When Start Monetization is clicked, the state changes to
pending, then to
started after Web Monetization initializes.
A non-web monetized visitor will see "Not enabled in browser" as the state, regardless of which button is clicked.
The example doesn't require you to have Web Monetization enabled in your browser. No real payments are occurring.
Click the View as Web Monetized/non-Web Monetized visitor button to toggle your monetization state.
If you see the source files instead of the example, click View App in the bottom right.