Topic on Talk:Edit Review Improvements/New filters for edit review

How can user scripts know when to run?

4
Evad37 (talkcontribs)

There are plenty of user scripts for the watchlist/recent changes, see w:en:Wikipedia:User_scripts/List#Listings. How can such scripts know when to run?

The usual strategy is to wait for document ready (by wrapping with $( function($) { });), then load dependencies (with mw.loader.using()), then run code that interacts with the page. With new filters active, this doesn't always work. E.g. with my WikidataWatchlistLabels script, it will sometimes work (show labels for wikidata Q and P numbers) on page load, and other times not work. And of course the results can be reset, e.g. if a filter is removed, and the script doesn't know that it should run again.

Trizek (WMF) (talkcontribs)

I've forwarded your question to the developers.

Roan Kattouw (WMF) (talkcontribs)

The recommended strategy for user scripts and gadgets modifying the content on the page is to use the wikipage.content hook:

mw.hook( 'wikipage.content' ).add( function ( $content ) {
    $content.find( 'li.mw-changeslist-src-mw-wikibase > span.comment > a.external' ).each( function () {
        // etc etc
    } );
} );

The wikipage.content hook is fired when the page first loads, and also by the new filters code every time the results are reloaded (and by some other pieces of code as well). The $content parameter tells you what was reloaded. On page load, it's the #mw-content-text div, and in the new filters UI it's the .mw-changeslist div and the .rcoptions fieldset (i.e. it's called twice for every refresh). Because the hook is sometimes called multiple times, and $content is sometimes something that doesn't contain the thing you're interested in, it's recommended that you use $content.find( '...' ) as much as possible, so that if $content is an unrelated part of the page, that'll find zero elements and do nothing.

Does that make sense? Unfortunately there isn't any good documentation about this on mediawiki.org :(

Evad37 (talkcontribs)
Reply to "How can user scripts know when to run?"