MutationSummary - observe a specific attribute on

2019-09-14 15:55发布

I've written a Greasemonkey userscript for kat.cr that adds a few extra buttons inside the 'Torrents awaiting feedback' popup.

The procedure is this: (provided that you have login and that you have some downloaded some torrents that "await feedback"):
after you click the FEEDBACK button, the 'Torrents awaiting feedback' popup appears,
containing the torrents that await feedback,
i.e. the style.display attribute of e.g. the element #fancybox-wrap becomes from none to block (as I've noticed in Firefox Inspector).

I currently use setTimeout to insert delay until the popup appears.

I want to improve the script.
So, I want to use MutationSummary (as a more practical solution to MutationObserver)
in order to monitor the change in the attribute style.display on the above element,
and add my extra buttons after that change occurs.

My code's structure is like this:

document.querySelector('.showFeedback > a').addEventListener('click', function () {

  var observer = new MutationSummary({
    callback: myF,
    queries: [
      {
        element: '#fancybox-wrap',
        elementAttributes: 'style.display'
      }
    ]
  });

  function myF(muteSummaries) {
    var mSummary = muteSummaries[0];
    mSummary.valueChanged.forEach(function(changeEl) {
      console.log('Attribute changed'); // Here I would add my code of inserting the extra buttons
    }      

});

Unfortunately the console.log is not executed.
Note that if I change elementAttributes: 'style.display' to elementAttributes: 'style'
then I get TypeError: mSummary.valueChanged is undefined in Browser Console.

How can I fix this?


Here is a working version of the code using MutationObserver:

document.querySelector('.showFeedback > a').addEventListener('click', function() {

    var target1 = document.querySelector('#fancybox-wrap');

    var observer1 = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (document.querySelector('#fancybox-wrap').style.display == 'block') {
                console.log('Attribute changed');
            }
        });
    });

    var config = {
        attributes: true,
        childList: true,
        characterData: true
    };

    observer1.observe(target1, config);

});

0条回答
登录 后发表回答