There are some websites that will auto add '(1 message)' in the front title, and I want to remove the characters added.
I try to use 'observe' to the element title to keep it as original in a Tampermonkey script, but some pages work, some pages with the same host do not.
Even it seems that it doesn't get the real original title of the page that run-at the document-start, and it will work one time after the title changes again.
So that means that the page title keeps adding '(1 message)' no matter when the title deletes '(1 message)'.
Is there another way to keep the title as original or did I miss something in the following code?
// identify an element to observe
var originalInnerHTML = document.getElementsByTagName("title")[0].innerHTML;
var elementToObserve = window.document.getElementsByTagName("title")[0];
// create a new instance of 'MutationObserver' named 'observer',
// passing it a callback function
const observer = new MutationObserver(function(mutationsList, observer) {
console.log(mutationsList);
var titleElement=document.getElementsByTagName("title")[0];
titleElement.innerHTML = originalInnerHTML;
observer.disconnect();//stop the MutationObserver
});
// call 'observe' on that MutationObserver instance,
// passing it the element to observe, and the options object
observer.observe(elementToObserve, {characterData: true, childList: true, attributes: true, subtree: true});
The observer should work. The thing that jumps out is that you're disconnecting the observer the first time it sees a change. So it won't see the next change. To fix that, remove the call to disconnect.
If you fix that but find that the observer isn't reliable (which would surprise me), then I'd take a simple-minded approach to it:
const originalTitle = document.title;
setInterval(() => {
document.title = originalTitle;
}, 100);
That will grab the title when the code runs and then repeatedly replace the old title with it, every 10th of a second. (Or make it every fourth of a second — 250ms — or whatever.) Note that browsers will de-prioritize timers in inactive tabs, but that should affect their code updating the title as much as your code updating the title.
(Side note: I've used document.title there, as it's simpler than the getElementsByTagName("title")[0].innerHTML approach.)