Skip to content

Instantly share code, notes, and snippets.

@camjocotem
Last active April 22, 2020 01:35
Show Gist options
  • Select an option

  • Save camjocotem/a71d306489583e6c86caa7640edd5774 to your computer and use it in GitHub Desktop.

Select an option

Save camjocotem/a71d306489583e6c86caa7640edd5774 to your computer and use it in GitHub Desktop.
Chat Filter
// Select the node that will be observed for mutations
window.filterApplied = false;
const targetNode = document.getElementsByClassName('top-nav__search-container')[0];
const chatNode = document.getElementsByClassName('chat-list__list-container')[0];
targetNode.parentElement.parentElement.innerHTML = `
<div style="display: flex;">
<input type="text" id="usernameFilter">
<button onclick="filterChat()">Filter</button>
<button onclick="clearfilter()">Clear</button>
</div>`
+ targetNode.parentElement.parentElement.innerHTML;
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for(let mutation of mutationsList) {
if(mutation.addedNodes){
if(window.filterApplied){
filterChat();
}
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(chatNode, config);
// Later, you can stop observing
//observer.disconnect();
function filterChat(){
let filterName = document.getElementById('usernameFilter').value;
if(!filterName){
return;
}
[].slice.call(document.getElementsByClassName('chat-list__list-container')[0].children)
.forEach(el => {
if(el.innerText === "Welcome to the chat room!"){
return;
}
let userNameTemp = el.innerText.match(/.+\:/);
if(userNameTemp){
userNameTemp = userNameTemp[0];
}
else{
return;
}
let userName = userNameTemp.slice(0,userNameTemp.length-1);
if(filterName.toLowerCase() !== userName.toLowerCase()){
el.style.display = "none";
}
else{
el.style.display = "block";
}
});
filterApplied = true;
}
function clearfilter(){
[].slice.call(document.getElementsByClassName('chat-list__list-container')[0].children)
.forEach(el => {
el.style.display = "block";
});
filterApplied = false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment