Search code examples
javascriptuserscripts

Monitor a tag for style changes with javascript?


I want my userscript to monitor this tag for changes:

<div id="moni" style="text-align: center; width: 773px; display: none; ">Offline</div>

The changes are to the style. display:none; sometimes changes to display:block;.

How do I monitor this through javascript?


Solution

  • Is your real goal to just keep that div from displaying?
    If so, then just use CSS in your script, like so:

    GM_addStyle ('#moni {display: none !important;}');
    

    But, if you really want to monitor for changes, here are some choices:

    1. Poll for changes. This is the simplest, most robust method.
      For example (No jQuery required):

      function checkForMoniDisplayChange () {
          this.lastDisp   = this.lastDisp  ||  "";
          var moniDiv     = document.getElementById ("moni")
          var moniDisp    = window.getComputedStyle (moniDiv).getPropertyValue ("display");
      
          if (moniDisp != this.lastDisp) {
              // DO SOMETHING
              //console.log (moniDisp);
          }
          this.lastDisp   = moniDisp;
      }
      
      //--- 150 is a good compromise between UI response and browser load.
      window.setInterval (checkForMoniDisplayChange, 150);
      


    2. Hook into the target-page's javascript that is making the change (if any).
      For example, if the target page uses the javascript function display (elem) to show that node, then you can often inject code similar to:

      var _old_display    = display;
      var display         = function (elem) {
          // DO SOMETHING
          _old_display (elem);    // Optional, depending on your goals.
          // DO SOMETHING MORE
      };
      


    3. Use the brand-new MutationObservers to monitor the element for changes to its class and/or style attributes.
      If you are going to do this, it's best to do it via Google's Mutation Summary library. Ask a new question for more information on this approach.


    Note that for security reasons, javascript cannot detect every style change. For example, your script won't be able to get the color of visited links.