Skip to content

Instantly share code, notes, and snippets.

@Bemmu Bemmu/tally.js
Last active Sep 19, 2017

What would you like to do?
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) {
// 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
You can’t perform that action at this time.