I've been maintaining a small project written in React. It's a browser extension which adds Slack-like emoji support to Facebook Messenger. Since Facebook is changing up thing once in a while, I need to make new changes to the browser extension, so they work just like before.
Facebook uses a <div> with the contenteditable attribute set to true. They have done this for as long as I remember. However, they changed something up, because I used to be able to do:
document.querySelector("div[contenteditable=true]").addEventListener(e => {
if(e.key == "Enter" && isActive) { //isActive means if the emoji picker is visible or not
e.preventDefault();
e.stopPropagation();
selectEmoji();
}
});
However, that event no longer fires, even though the element exists. It fires for EVERY key except Enter. So I started digging with a MutationObserver, and to my surprise, I noticed this:
removedNodes: NodeList[<div with contenteditable=true>]
addedNodes: NodeList[NEW <div with contenteditable=true>]
So once I hit enter, Facebook sends the message and then replaces the entire "chatbox" element (the div with contenteditable=true) with a new chatbox element.
What I don't understand, is how my addEventListener isn't firing, when I hit the Enter key. Even if I do something like this, it won't work:
setInterval(() => {
var chatbox = document.querySelector("div[contenteditable=true]");
chatbox.addEventListener("keydown", () => ........ });
}, 1000);
Even if Facebook is removing the element, shouldn't my event fire anyway? According to my test here, it should fire (at least the first time): https://jsfiddle.net/web4dyg1/
Since adding an event listener, and then cancel Facebook's request (previously form submission), doesn't work anymore, what other options do I have? I know this question is really niche, but I was hoping someone had an thinking-out-of-the-box idea.
EDIT: I need to clarify that adding the event listener works. Every single keypress fires the event EXCEPT for the Enter key.