How to use Jquery to trigger a function when the page title is changed?

Asked

Viewed 27 times

0

Hello, I am new on this platform, I do not know if my question will meet the requirements, but I will try to be as specific as possible!

I want to trigger an event using Jquery, so when changed, I was trying to use the following function:

$('title').change(function(){
console.log('O titulo foi alterado!')
})

But when I change the value of the tag, nothing happens, someone could explain to me why, or if it is possible to present me a valid way to do this.. From now on :D!

  • You change the value of title through a input?

  • No, through the devtools

  • Actually, I want this event to be triggered when I receive a new message on Whatsapp, when there is a message on Whatsapp its title is changed and I want to capture this event

1 answer

0


if I can be presented with a valid way of doing this..

Using pure Javascript you can use the MutationObserver which is an API that observes changes in the DOM and triggers a function when it detects it.

For example, you select the title via querySelector and assigns it to instance MutationObserver using the method observe. Run a function of callback for the object MutationObserver triggers when a change occurs in the title.

Sample code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const title = document.querySelector('title');

      new MutationObserver(function (mutations) {
        console.log(mutations[0].target.nodeValue); // mostra o novo valor

        console.log('Title mudou!'); // avisamos que o title mudou
        alert('Title mudou!')
      }).observe(title, { // informamos que ele deve observar 'title'
        subtree: true,
        characterData: true,
        childList: true,
      });
    </script>
  </body>
</html>

I don’t know if this API is implemented in Jquery.

  • woww! thank you very much worked perfectly well, THANK YOU very much !

  • And if I wanted to observe a class for example, it would work?

  • If you speak of an element with a specific class yes, just do const elemento = document.querySelector('.nome-da-classe);. Pass .nome-da-classe to the querySelector. Can be id, class, tag, etc...

  • OK thank you very much!

Browser other questions tagged

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