Events & Custom JS
The Miso Answers SDK emits events while it works. You can listen to those events and run your own JavaScript, or code from another vendor. Use this to log responses, to intercept a link inside an answer, or to connect Miso to a paywall such as Piano.
This page assumes you already have the SDK on your page. See Ask — Quick Start for the install.
Listen to answer data
Every workflow on the client emits a data event. The event fires each time
the SDK receives a response from the Miso API.
const client = new MisoClient("YOUR_PUBLISHABLE_API_KEY");
const context = client.ui.asks;
context.on("data", ({ status, value }) => {
if (!value) return;
console.log("API response", value);
});
| Field | What it holds |
|---|---|
status |
Where the workflow is: it is still loading, or it is ready. |
value |
The API response. It is empty until the first data arrives. |
The event fires more than once for one question, because Miso streams the
answer. Test value before you read it.
For every event the SDK emits, see the SDK events reference.
Intercept a link inside an answer
Miso can put a link in an answer. A metering message is the common case:
You reached your limit of free answers. Please sign in or register to continue.
The URL of each link ends with a hash that you choose, for example
#miso-reg-click. Your page can listen for a click on that hash, stop the
navigation, and run your own flow instead. You configure the message and the
hash with Miso. See Metering & Entitlements.
Example: open the Piano registration flow
This listener catches a click on any link that ends with #miso-reg-click. It
then starts Piano's login flow instead of following the link.
const TARGET_HASH = "#miso-reg-click";
document.addEventListener("click", (event) => {
const link = event.target.closest("a");
if (!link) return;
const href = link.getAttribute("href");
if (!href || !href.endsWith(TARGET_HASH)) return;
event.preventDefault();
const tp = (window.tp = window.tp || []);
tp.push([
"addHandler",
"loginRequired",
(params) => {
// Keep the Piano state in a cookie, for the login page to read.
const oneHour = new Date(Date.now() + 60 * 60 * 1000);
document.cookie =
"__pianoParams=" +
encodeURIComponent(JSON.stringify(params)) +
"; expires=" + oneHour.toUTCString() +
"; path=/; domain=.example.com";
location.href = "https://example.com/login";
},
]);
tp.push(["showLogin"]);
});
Three things to change for your site:
TARGET_HASHmust match the hash in the message that Miso returns.- The cookie
domainmust be your domain. location.hrefmust be your login or registration page.
The listener is on document, so it also works for an answer that arrives
after the page loads.
Summary
| Hook | What you can do with it |
|---|---|
The data event |
Read each API response as it arrives. Log it, or send it to your own analytics. |
| A link click inside an answer | Stop the navigation and run your own flow, such as a paywall or a login. |
