Wikipedia:User scripts/Guide: Difference between revisions

Content deleted Content added
Your first script: update. resolve {{Why}} tag
update
Line 106:
</syntaxhighlight>
 
Save this to your ''User:YourUserName/common.jsj''s page. Then go visit a page such as the [[Wikipedia:Sandbox|Sandbox]], go into the "More" menu, click "Wikify", and watch the user script add the maintenance tag for you.
 
== Built-in scripts ==
Line 166:
 
=== Text editors ===
You can use anything from a simple [[text editor]], to a more feature-packed [[code editor]] or [[Integrated development environment|IDE]]. Here are some featuresrecommended weeditors, recommend:by operating system.
 
* Color code JavaScript code
* Quickly insert standard JavaScript keywords and methods ([[code completion]])
** With the help of type definition libraries, you may also get code completion for the [[#Built-in scripts|globally available objects]] of [https://www.npmjs.com/package/types-mediawiki MediaWiki], [https://www.npmjs.com/package/@types/jquery jQuery], [https://www.npmjs.com/package/@types/oojs OOjs], and [https://www.npmjs.com/package/@types/oojs-ui OOUI].
* Show the list of all functions and quickly jump to any function
 
Here are some recommended editors, by operating system.
 
* Windows
Line 453 ⟶ 446:
One way to coordinate this is use the [https://doc.wikimedia.org/mediawiki-core/master/js/Hooks.html mw.hook] interface. Perhaps the other script sends a <code>[[#mw.hook('wikipage.content').add(...)|wikipage.content]]</code> event when it is done, or can be modified to do so (or you can ask the maintainer).
 
Another way to avoid this is to use a [https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver MutationObserver].
Another way to avoid this is to use the <code>DOMNodeInserted</code> or <code>DOMNodeRemoved</code> events to listen for when the other user script is finished, ensuring that your user script executes last.
 
<syntaxhighlight lang="javascript">$('body').on('DOMNodeInserted', '.preferences-link.link', function() {
// do things
}</syntaxhighlight>
 
=== User settings ===
Line 477 ⟶ 466:
Your code here.
 
//</nowiki></syntaxhighlight>If you need to print &lt;nowiki&gt; or &lt;/nowiki&gt; tags within your user script, use a trick such as <code>const tag = '</' + 'nowiki>';</code> to keep from messing up the nowiki tag on line 1 and on the last line.
//</nowiki></syntaxhighlight>
 
=== Function scope ===
Line 487 ⟶ 476:
$(function(){/* main code here */});</syntaxhighlight>
 
What if another of your user scripts also declares a <code><nowiki>submitEdit()</nowiki></code> function, but you have modified the code? This can lead to [[race conditions]] and hard-to-trace bugs. Instead, use classes named after your script, or place all your functions inside of an [[immediately invoked function expression]] (IIFE) such as <code><nowiki>$(function {});</nowiki></code>. JavaScript allows [[Nested function|nested functions]].
 
<syntaxhighlight lang="javascript">$(function(){
Line 496 ⟶ 485:
 
== Ajax ==
[[Ajax (programming)|AJAX]] (''asynchronous JavaScript and XML'') is a popular name for a web programming technique that queries the server or fetches content without reloading the entire page. This is great for API requests. We do not have access to the SQL database in front end code, so the [[mw:Action_API|MediaWiki action API]] (or one of the [[mw:REST_API|other APIs]]) is the main way we retrieve data.
 
Although programming AJAX can be complex, libraries of functions can make it much easier. Since the [[mw:MediaWiki 1.16|1.16 release]], MediaWiki comes with the [[jQuery]] library, providing a convenient framework for easily making Ajax requests.
 
===Common problems===
* <p>AJAX programmers commonly run into problems if they do not account for AJAX's ''asynchronicity''. If you try to pop up a box with another page's content, you will almost certainly pop up a box containing <code>'''null'''</code>. This occurs because the script continued even though the query wasn't finished.</p><!--
 
--><p>To correct the problem, you need to use [[w:callback (computer science)|callback functions]]. Place the next portion of code after a query into a function, and call the function when the query completes. jQuery makes this easy to do.</p>
* AJAX scripts cannot reach a page on a different server (for example, ''google.ca'' or ''en.wikisource.org'' from ''en.wikipedia.org''). Trying to do so will cause the script to halt with or without error. This can be circumvented using a proxy on the current server, but none is available for Wikimedia user scripts.
 
=== Basic examples ===
==== mediawiki.api ====
MediaWiki provides some modules with helper functions facilitating the use of its API. The main modules available are
* [https://doc.wikimedia.org/mediawiki-core/master/js/mw.Api.html mediawiki.api]
Line 514 ⟶ 496:
 
Be sure to follow the [[meta:User-Agent policy|user agent policy]] by setting a user agent header (see code there). See also [[mw:API:Etiquette]].
 
==== Fetch page content ====
Fetching a page content can be done using [[GET (HTTP)|GET]].
<syntaxhighlight lang="javascript">
$.ajax({
url: mw.util.getUrl( 'Wikipedia:Sandbox' )
})
.then(function( data ) {
alert( 'The remote page contains:\n' + data );
})
.catch(function() {
alert( 'The ajax request failed.' );
});
</syntaxhighlight>
 
==== Get the wikitext of a page ====
 
===== Using module <code>mediawiki.api</code>=====
Note: make sure to add <code>mediawiki.api</code> to your dependencies!
Line 561 ⟶ 528:
</syntaxhighlight>
 
===== Using plain jQuery $.getJSON =====
<syntaxhighlight lang="javascript">
$.getJSON(
Line 588 ⟶ 555:
</syntaxhighlight>
 
====Edit= aUsing pagejQuery and$.ajax other common actions=====
Fetching a page content can be done using jQuery <code>$.ajax</code>, which does an HTTP [[GET (HTTP)|GET]] request.<syntaxhighlight lang="javascript">
$.ajax({
url: mw.util.getUrl( 'Wikipedia:Sandbox' )
})
.then(function( data ) {
alert( 'The remote page contains:\n' + data );
})
.catch(function() {
alert( 'The ajax request failed.' );
});
}</syntaxhighlight>
 
==== Edit a page and other common actions ====
Scripts can perform common actions (like editing, protection, blocking, deletion, etc.) through the [{{SERVER}}/w/api.php API]. These actions require an edit token, valid for any action during the same session. (However, you should get a new token for different tasks in case this changes in the future.)
 
Line 686 ⟶ 666:
== Working with CSS ==
 
Some user scripts also use some CSS code, or even are built with CSS only. Then you need to code and test CSS code. That can be done invia editing your ''User:YourUserName<kbd>/common.css</kbd>,'' but it is slow and messy<kbd>page.</kbd>
 
=== Loading a localhost file ===
InsteadFor local development only, you can load a CSS file from your local web server (see the previous section for an easy-to-install web server). Put this line at the top of your [[Special:Mypage/common.css|/common.css]]:
<syntaxhighlight lang="css">
@import "http://localhost/wikipediatest.css";