MutationObserver in Tampermonkey script always misses the first node

61 Views Asked by At

I have the following Tampermonkey custom script:

// ==UserScript==
// @name         Hacker News
// @namespace    https://news.ycombinator.com/*
// @version      2024-02-02
// @description  try to take over the world!
// @author       You
// @match        https://news.ycombinator.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @grant        none
// ==/UserScript==

var observer = new MutationObserver(mutations => {
  mutations.forEach(mutation => {
    if (mutation.type === "childList" && mutation.addedNodes && mutation.addedNodes.length > 0 && mutation.addedNodes[0].nodeType == Node.ELEMENT_NODE) {
      // console.log(`${mutation.addedNodes.length}, ${mutation.type}, ${mutation.addedNodes[0].nodeType}`);
      // console.log(mutation.addedNodes[0]);
      // console.log(mutation.addedNodes[0]);
      Array.from(mutation.addedNodes[0].querySelectorAll('span.titleline')).forEach (element=> {
        console.log(`Matched: ${element.innerText}`);
        element.style.background = 'yellow';
        if (window.webkit) {
            window.webkit.messageHandlers.gotData.postMessage(element.innerText);
        }
      });
    }
  });
});

observer.observe(document, {
    attributes: true,
    childList: true,
    characterData: true,
    subtree: true
  }
);

It works okay in Chrome but in Firefox, it always misses the first node.

It looks like this in my Firefox plugins:

enter image description here

Settings look like this. I have set the Run at: setting to document-start as shown in the 2nd screenshot. First node shouldn't be part of the document at this time from what I understand:

enter image description here

For some reason, it always misses the first post on the Hacker News page:

enter image description here

Am I missing something special in Firefox?

EDIT:

I have just noticed that when the reload happens, the first node is "escaping" the mutation observer for some reason. I recorded a video of this. It's hard to notice, so you may have to pause the video to look at that frame:

https://i.imgur.com/SUTYwPD.mp4

I was able to capture a screenshot of that very frame:

https://i.imgur.com/RLNcBB7.png

Notice how the first node is loaded, rest haven't loaded when MutationObserver kicks in. So the first node escapes it. Why's this? The HTML is rendered server side by Hacker News, so this shouldn't happen from what I understand.

0

There are 0 best solutions below