In any web application, you commonly want to track custom data: for example, when a user clicks a button on a specific page of your website. Google Analytics calls these events, and we'll use the same language in this context.
In this example, we'll show you how to send a custom event to a RequestBin endpoint each time a user clicks a button on a webpage, and how to examine these events in the inspector.
First, you'll need to create a new endpoint specific to this custom event and have the endpoint URL ready for the next step.
We're going to create the simplest possible webpage - a single button that sends a custom HTTP request to our endpoint when a user clicks the button:
<!DOCTYPE html>
<html>
<head>
<title>Custom Event Test</title>
<script type="text/javascript">
function sendCustomEvent() {
const headers = new Headers();
headers.append("Content-Type", "application/json");
const body = { event: "button-click" };
const options = {
method: "POST",
headers,
mode: "cors",
body: JSON.stringify(body)
};
fetch("https://test.x.pipedream.net/", options);
}
</script>
</head>
<body>
<button type="button" onclick="sendCustomEvent()">Click Here</button>
</body>
</html>
Replace test.x.pipedream.net
with your endpoint URL you created above, save this code snippet as an HTML file, and open it in your browser.
Clicking on the Click Here button should trigger two HTTP requests:
OPTIONS
request to ensure the endpoint accepts cross-origin HTTP requests from this domain. Since we accept any cross-origin HTTP requests, this request should succeed.POST
request sends the actual custom event data sent by the sendCustomEvent
function in the snippet above.The first, preflight request should not appear in the UI, but the POST
request should. You should see the JSON body sent in the custom event in the inspector.
You can modify this example however you see fit, using it to track any custom event, passing any additional data in the event body. This can be helpful for troubleshooting, better understanding user behavior, and more.
You're not limited to sending custom event data from a browser. You can send HTTP requests to an endpoint from any source. Take a look at the example code we've provided to get started.
Please reach out with any questions or suggestions.