Created
February 21, 2022 10:57
-
-
Save michelefenu/fcdb86a8b6954341919ca9e9b5c229a4 to your computer and use it in GitHub Desktop.
Replace all text in a webpage with random characters
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
"use strict"; | |
function isExcluded(elm) { | |
if (elm.tagName == "STYLE") { | |
return true; | |
} | |
if (elm.tagName == "SCRIPT") { | |
return true; | |
} | |
if (elm.tagName == "NOSCRIPT") { | |
return true; | |
} | |
if (elm.tagName == "IFRAME") { | |
return true; | |
} | |
if (elm.tagName == "OBJECT") { | |
return true; | |
} | |
return false | |
} | |
function traverse(elm) { | |
if (elm.nodeType == Node.ELEMENT_NODE || elm.nodeType == Node.DOCUMENT_NODE) { | |
// exclude elements with invisible text nodes | |
if (isExcluded(elm)) { | |
return | |
} | |
for (let childNode of elm.childNodes) { | |
// recursively call to traverse | |
traverse(childNode); | |
} | |
} | |
if (elm.nodeType == Node.TEXT_NODE) { | |
// exclude text node consisting of only spaces | |
if (elm.nodeValue.trim() === "") { | |
return | |
} | |
// Pass true as second parameter to replace with letters | |
elm.nodeValue = replaceText(elm.nodeValue); | |
} | |
} | |
function replaceText(text, fillAlphabet = false) { | |
let out = []; | |
for (let char of text?.split('')) { | |
if (char === ' ') { | |
out.push(char); | |
} else { | |
const replacement = fillAlphabet ? generateRandomLetter() : 'x'; | |
if (/[a-z]/.test(char)) { | |
out.push(replacement); | |
} else { | |
out.push(replacement.toUpperCase()); | |
} | |
} | |
} | |
return out.join(''); | |
} | |
function generateRandomLetter() { | |
const alphabet = 'abcdefghijklmnopqrstuvwxyz'; | |
return alphabet[Math.floor(Math.random() * alphabet.length)] | |
} | |
traverse(document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment