MutationSummary - observe a specific attribute on an element, and execute some code after that attribute gets a specific value

孤人 提交于 2020-01-07 04:44:14

问题


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);

});

来源:https://stackoverflow.com/questions/34010044/mutationsummary-observe-a-specific-attribute-on-an-element-and-execute-some-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!