Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created April 9, 2023 13:07
Show Gist options
  • Save bennadel/c4cc3c2cf7abf3b8cfc708393eee4195 to your computer and use it in GitHub Desktop.
Save bennadel/c4cc3c2cf7abf3b8cfc708393eee4195 to your computer and use it in GitHub Desktop.
Using navigator.sendBeacon() To Publish Analytics Back To ColdFusion
<cfscript>
param name="url.test" type="string";
requestData = getHttpRequestData();
// We're going to echo-back the type of beacon data that we received.
response = [
contentType: requestData.headers[ "Content-Type" ],
method: cgi.request_method,
form: form,
url: url,
body: requestData.content
];
// NOTE: According to the sendBeacon() specification, since the API doesn't expose a
// response on the client, the server is encouraged to omit any content in the
// response body and just send back a "204 No Content" status. However, for the sake
// of experimentation, I am echoing back the data that was sent (so we can see it in
// the Developer tools Network tab).
content
type = "application/x-json"
variable = charsetDecode( serializeJson( response ), "utf-8" )
;
</cfscript>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<h1>
Using navigator.sendBeacon() To Publish Analytics Back To ColdFusion
</h1>
<button id="myButton">
Send Beacon
</button>
<script type="text/javascript">
var clickCount = 0;
myButton.addEventListener(
"click",
( event ) => {
clickCount++;
// When sending Beacon data, we can use a variety of different types of
// payload. Let's try sending various encodings so that we can see how
// they arrive on the ColdFusion server.
sendAsString();
sendAsFormData();
sendAsSearchData();
sendAsBlob();
}
);
// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
function sendAsString() {
var data = `click|clickCount:${ clickCount }`;
navigator.sendBeacon( "./analytics.cfm?test=sendAsString", data );
}
function sendAsFormData() {
var data = new FormData();
data.set( "interaction", "click" );
data.set( "clickCount", clickCount );
navigator.sendBeacon( "./analytics.cfm?test=sendAsFormData", data );
}
function sendAsSearchData() {
var data = new URLSearchParams();
data.set( "interaction", "click" );
data.set( "clickCount", clickCount );
navigator.sendBeacon( "./analytics.cfm?test=sendAsSearchData", data );
}
function sendAsBlob() {
var data = new Blob(
[
JSON.stringify({
interaction: "click",
clickCount: clickCount
})
],
{
type: "application/x-json"
}
);
navigator.sendBeacon( "./analytics.cfm?test=sendAsBlob", data );
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment