Last active
January 22, 2019 21:44
-
-
Save matchu/6d9633011ceb74af724894818e7fa188 to your computer and use it in GitHub Desktop.
"Has bad words?" script for Neopets textareas [needs word list!]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ALL_BAD_WORDS = [ | |
// Except, like, replace this with the actual list of words. | |
"uncle", | |
"grape" | |
]; | |
/** Return a list of bad words that appear in the given text. */ | |
function findBadWords(text) { | |
return ALL_BAD_WORDS.filter(badWord => text.includes(badWord)); | |
} | |
/** Given a textarea, check for bad words. If so, log them & style the box. */ | |
function checkTextarea(textarea) { | |
const badWords = findBadWords(textarea.value); | |
const hasBadWords = badWords.length > 0; | |
textarea.classList.toggle("has-bad-words", hasBadWords); | |
for (const badWord of badWords) { | |
console.log("Text contains the following bad word:", badWord); | |
} | |
} | |
/** Add "has-bad-words" CSS class to the document, for use in checkTextarea. */ | |
function addCSS() { | |
// Add the red-background styles as a CSS class, so we can quickly toggle | |
// it as the user types, without polluting local styles. | |
const node = document.createElement("style"); | |
node.type = "text/css"; | |
node.innerHTML = ` | |
/* Injected by Neopets has-bad-words bookmarklet. */ | |
.has-bad-words { | |
background: #faa !important; | |
} | |
`; | |
document.body.appendChild(node); | |
} | |
/** Handle any change event on the page. If it's for a textarea, check it. */ | |
function handleChange(event) { | |
if (event.target.tagName === "TEXTAREA") { | |
checkTextarea(event.target); | |
} | |
} | |
/** Add global event listeners for all textarea change events. */ | |
function addListeners() { | |
// Listen for all change and keyup events, to catch keyboard & non-keyboard | |
// changes. This will trigger some false positives (i.e. key presses not in | |
// textareas), but `handleChange` quickly checks and ignores that case. | |
document.addEventListener("change", handleChange, true); | |
document.addEventListener("keyup", handleChange, true); | |
} | |
/** Check all textareas proactively, instead of waiting for them to change. */ | |
function checkAllTextareas() { | |
const textareas = document.querySelectorAll("textarea"); | |
for (const textarea of textareas) { | |
checkTextarea(textarea); | |
} | |
} | |
// To start up, add the CSS, add the event listeners, and check all textareas | |
// in case they already contain bad words. | |
addCSS(); | |
addListeners(); | |
checkAllTextareas(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment