Search code examples
javascriptc#webbrowser-controlgeckofx

What is the appropriate event listener for a page that change its content using XMLHttpRequest?


By using the GeckoWebBrowser in C# is there anyway to know when a page has completed updating its content using XMLHttpRequest ? I thought that the DocumentCompleted event would have done it but since the page it's not reloading it wont fire up...


Solution

  • You could use a mutation observer watching document.body's subtree, and assume that the page has finished being modified (say) 20ms after the last notification you get.

    In JavaScript, that would look something like this:

    (function() {
      var observer;
    
      // The click handler that appends content after a random delay
      document.querySelector('input').addEventListener("click", function() {
        if (!observer) {
           hookupObserver();
        }
        setTimeout(function() {
          var p = document.createElement('p');
          p.innerHTML = "New content added at " + Date.now();
          document.querySelector('div').appendChild(p);
        }, 500 + Math.round(Math.random() * 500));
      }, false);
      
      // Watching for subtree mods to `document.body`:
      function hookupObserver() {
        var timer = 0;
        observer = new MutationObserver(function() {
          clearTimeout(timer);
          timer = setTimeout(done, 40);
        });
        observer.observe(document.body, {childList: true, subtree: true});
      }
      
      function done() {
        timer = 0;
        alert("Modification complete");
      }
    })();
    <input type="button" value="Click to simulate async modification">
    <div>This is the page</div>