Skip to content

Instantly share code, notes, and snippets.

@Bemmu
Last active September 19, 2017 18:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bemmu/81ffcb95af3cd553e2ea2037c870ec91 to your computer and use it in GitHub Desktop.
Save Bemmu/81ffcb95af3cd553e2ea2037c870ec91 to your computer and use it in GitHub Desktop.
Highlighting tally
// I had to write this code in just a few minutes to get it ready while my article was still trending.
// I decided to exclude anyone not on desktop Chrome to avoid spending time on browser issues.
// Here I am trying to test if the user is on desktop Chrome.
function onDesktopChrome() {
var pattern = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|mobile|CriOS/i;
var isMobile = pattern.test(navigator.userAgent);
if (isMobile) {
return false;
} else {
// On desktop, now exclude non-Chrome browsers
if (!/Chrome/i.test(navigator.userAgent)) {
return false;
}
}
return true;
}
// The highlight count is maintained by detecting mouse clicks and seeing if something was selected.
var highlightCount = 0;
if (onDesktopChrome()) {
document.onmouseup = function () {
if (window.getSelection().toString().length > 0) {
highlightCount++;
}
}
}
// When the visitor leaves the page, their number of text selections is reported back. To make sure it reaches the server even after the page has unloaded, a somewhat little-known feature called a beacon is used.
if (onDesktopChrome()) {
window.addEventListener("unload", function () {
navigator.sendBeacon("/highlight_count", "" + textSelectionCount);
}, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment