Skip to content

Instantly share code, notes, and snippets.

@count23all
Last active November 8, 2024 04:16
Show Gist options
  • Save count23all/6eee9b3845e375c2cf522b6aa2fd0074 to your computer and use it in GitHub Desktop.
Save count23all/6eee9b3845e375c2cf522b6aa2fd0074 to your computer and use it in GitHub Desktop.
This userscript creates a CSS box on the right hand side of any Perplexity AI chat expressing the approximate word counter and token counter based on the openAI recommended 1 token ~= 0.75 words.
// ==UserScript==
// @name Perplexity Word Counter 2 (Dark Mode, Draggable)
// @namespace http://tampermonkey.net/
// @version 1.5
// @description Counts words on Perplexity search pages and estimates context, updates every 5 seconds, draggable
// @match https://www.perplexity.ai/search/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// Create and style the counter box
const counterBox = document.createElement('div');
counterBox.id = 'word-counter-box';
counterBox.style.cssText = `
position: fixed;
right: 20px;
top: 33%;
background-color: rgba(30, 30, 30, 0.9);
color: #ffffff;
border: 1px solid #444;
border-radius: 5px;
padding: 10px;
font-family: Arial, sans-serif;
font-size: 14px;
z-index: 9999;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
cursor: move;
user-select: none;
`;
// Function to count words
function countWords(text) {
return (text.match(/\S+/g) || []).length;
}
// Function to update the counter
function updateCounter() {
// Update selector to match divs with mb-md or my-md in their class names
const elements = document.querySelectorAll('div[class*="mb-md"], div[class*="my-md"]');
let totalWords = 0;
elements.forEach(element => {
totalWords += countWords(element.innerText);
});
const contextEstimate = Math.round(totalWords / 0.75);
counterBox.textContent = `Words: ${totalWords} | Context: ${contextEstimate}`;
}
// Add the counter box to the page
document.body.appendChild(counterBox);
// Initial update
updateCounter();
// Update counter every 5 seconds
setInterval(updateCounter, 5000);
// Make the box draggable
let isDragging = false;
let currentY;
let initialY;
let yOffset = 0;
function setTranslate(yPos) {
counterBox.style.transform = `translateY(${yPos}px)`;
}
function dragStart(e) {
initialY = e.clientY - yOffset;
isDragging = true;
}
function dragEnd() {
initialY = currentY;
isDragging = false;
}
function drag(e) {
if (isDragging) {
e.preventDefault();
currentY = e.clientY - initialY;
yOffset = currentY;
setTranslate(currentY);
}
}
counterBox.addEventListener('mousedown', dragStart);
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', dragEnd);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment