Skip to content

Instantly share code, notes, and snippets.

@FranciscoG
Created April 4, 2018 15:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save FranciscoG/01732b606a35615891103ae8e8e5a7a4 to your computer and use it in GitHub Desktop.
Save FranciscoG/01732b606a35615891103ae8e8e5a7a4 to your computer and use it in GitHub Desktop.
/*
Traverse through all the Text Nodes in a page and force them to display hidden characters
Sources:
Hacker news: https://news.ycombinator.com/item?id=16749422
user: tim333's js fiddle https://jsfiddle.net/tim333/np874wae/13/
medium post: https://medium.com/@umpox/be-careful-what-you-copy-invisibly-inserting-usernames-into-text-with-zero-width-characters-18b4e6f17b66
TODO:
1. Make this into an extension
2. Handle new dynamically inserted text nodes using... except that might be hard since mutation events are not
web standard so are not reliable: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
3. add filter to createTreeWalker to exlcude script and add more nodes that could contain text like inputs and stuff
*/
(function(){
/**
* search through string for hidden zero-width characters
* @param {String} val the string to parse
*/
function checkText(val) {
let ch = [...val];
return ch.reduce((prev, curr)=>{
let no = curr.codePointAt(0)
out = prev + curr;
if (no == 10) {
out += "\n"
}
if (no > 128) {
out += "[" + no + "]"
}
return out;
},'');
}
/**
* Searchs for all text nodes starting in at a given text element
* src: https://stackoverflow.com/a/10730777/395414
* @param {HTMLElement} el parent node to begin searching for text nodes from
*/
function getTextNodesUnder(el){
let n;
let a=[];
let walk = document.createTreeWalker( el, NodeFilter.SHOW_TEXT, null, false);
while(n=walk.nextNode()) a.push(n);
return a;
}
getTextNodesUnder(document.body).forEach(n=>{
n.nodeValue = checkText(n.nodeValue);
});
})();
@roymckenzie
Copy link

I pulled the code you adapted into a Chrome Extension. Check it out, maybe you can use your code in the extension? https://github.com/roymckenzie/detect-zero-width-characters-chrome-extension

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment