How to reload the Greasemonkey script when AJAX changes the URL without reloading the page?

I have an application that I am trying to create a Greasemonkey script for. It uses a lot of jQuery and AJAX to dynamically load content.

I noticed that the URL changes every time a new item is loaded, even if the page does not refresh.

Is there a listener that I can place on the page to restart the script every time the URL changes?

+7
javascript ajax greasemonkey
source share
2 answers

How you do this depends on the site / application and what you are trying to do. Here are your options , the simplest and most reliable:

  • Do not attempt to catch URL changes. Use the waitForKeyElements() calls to work on parts of the various pages that you wanted to manipulate in the first place. This neatly handles the whole time problems inherent in all other approaches.
    See Also: "Selecting and Activating the Right Controls on an AJAX-Managed Site . "

  • Just a poll to change the URL. It is simple and works in practice with fewer time issues than all but 1.

  • If the site uses AJAX, which modifies the fragment (AKA hash), the hashchange event lights up , Alas, fewer and fewer AJAX sites do this.

  • Use Mutation Observers to track changes to the <title> . Most AJAX pages are good enough to change the name. This may work before loading targeted content.

  • Hack history.pushState function. This gives a faster notification of changes to the page, BUT 95% of the time, it works before loading your target elements. You usually need a timer. In addition, it causes cross-region issues in the user interface environment.


For reference , an example survey is provided here . It is still the best cross-browser, boneless, catch-all method:

 /*--- Note, gmMain () will fire under all these conditions: 1) The page initially loads or does an HTML reload (F5, etc.). 2) The scheme, host, or port change. These all cause the browser to load a fresh page. 3) AJAX changes the URL (even if it does not trigger a new HTML load). */ var fireOnHashChangesToo = true; var pageURLCheckTimer = setInterval ( function () { if ( this.lastPathStr !== location.pathname || this.lastQueryStr !== location.search || (fireOnHashChangesToo && this.lastHashStr !== location.hash) ) { this.lastPathStr = location.pathname; this.lastQueryStr = location.search; this.lastHashStr = location.hash; gmMain (); } } , 111 ); function gmMain () { console.log ('A "New" page has loaded.'); // DO WHATEVER YOU WANT HERE. } 
+11
source share

“I noticed that the URL changes every time,” as many AJAXs lead me to use the history API. If this happens, see window.onpopstate . This should work every time the URL changes using the history API.

0
source share

All Articles