How to observe an element that is added and removed from code

Asked

Viewed 22 times

0

Hello, the title of my question may seem a bit confusing, but I’m studying to make an extension to Whatsapp, I want to be able to print a log saying that there is a new message whenever you receive it, when we receive a message in Whatsapp an element appears with the class ". Vor2j", with this I believe it is possible to monitor whenever this class is added from the code. For this I tried to use the Mutationobserver API, which a friend suggested to me in another question of mine!

So I’m trying the following code:

var unreadMessage = document.querySelector('.VOr2j');
new MutationObserver(function () {
    console.log("Hey! Nova mensagem")
}).observe(unreadMessage, { 
    subtree: true,
    characterData: true,
    childList: true,
});

But I find the following mistake:

Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.
    at <anonymous>:4:4

I believe it is because this element does not yet exist in the code, but then as I can observe a class that is added and removed from the code every time I receive/read a message, I thank those who can help me !

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.