Wikipedia:User scripts/Guide

Prerequisites
To write user scripts, you'll have to learn at least some of the programming language that they are written in: JavaScript.

Try these links: Also, it would definitely help if you tried using one of our scripts and got it working. The rest of this tutorial assumes you know where the various things are (all explained at ).
 * Mozilla Developer Network's JavaScript site
 * W3schools Javascript tutorial
 * JavaScript syntax
 * jQuery

Forking an existing script
Starting out, it may be easier to modify an existing script to do what you want, rather than create a new script from scratch. This is called "forking". To do this, copy the script to a subpage, ending in ".js", of your user page. Then, install the new page like a normal user script.

Writing a script from scratch
While you can write a script directly in your common.js page or skin.js (such as vector.js) page, it is usually better to create a new subpage for it in the form YourUserName/title.js, where title is the name of your script. That keeps your main js pages from getting cluttered, which is helpful when you have multiple scripts installed. You will also want to install the new user script.

Hello world
To make a Hello world program, insert this code into your User:YourUserName/common.js file.

Next, create the page User:YourUserName/hello-world.js, and insert this code.

This will write "Hello world!" on every page, below the title, until you remove the code. User scripts are written in JavaScript, and both of the above code snippets are in JavaScript. The second snippet uses JQuery, which is a JavaScript library that specializes in manipulating HTML. is a JQuery function that lets us target the HTML element we want. is a string in CSS selector syntax, and means target the HTML element with property. is a JQuery function that inserts HTML code as a child of the  element. is the HTML code to be inserted.

Your first script
We will be writing an independent module by modifying your js, so you may want to get our module template. For the purpose of this tutorial, we will write a simple version of the Quick wikify module, which adds the  maintenance template to articles. To begin, change  in the module template to "Qwikify". Your template should look like this:

In, we want to add the "Wikify" tab, so we will use the   function (which requires the   module). Replace  with a call to this function. Then we'll bind an event handler so that when this link is clicked, we will call another function named  that will actually execute the code. The  is what is shown on the tab, so set that to. Most tabs have an ID of, so set the ID to. The title (also known as mouseover or rollover text) should be something like. Lastly, we use jQuery's [//api.jquery.com/click/ .click] to listen for clicks on this link, and when that happens, execute a function. After we call, it says. Since we clicked on a link, we need to tell the browser to prevent its default behavior (which is going to a the url, ). We want the page to stay right where it's at, so to prevent the browser from following the link, we prevent that and do our own custom action.

Altogether, your new function should look like this:

Now, we must write our actual  function. It will edit the edit box, so we need to get the name of that and its form. Viewing the source of the page shows that the form is named  and the textbox is named , meaning that the actual text is. To add wikify (and two new lines), we simply do:

(We separate the two "{" brackets in the front of the wikify template so it doesn't get expanded when we write this code on the wiki.)

Finally, we want to submit the form for the user. Luckily, JavaScript has a built-in function just for this named. To submit our editing form, use. Your code should now look something like this:

And that's it! Save the common.js and then do a hard refresh. Go and edit a page such as the Sandbox, and see what happens! Note that syntax highlighting must be disabled for this to work.

Built-in scripts
All Wikipedia pages include some built-in MediaWiki JavaScript code, with variables and functions that can be used in user scripts. Some of them were already mentioned. This code is generally loaded as ResourceLoader modules (some of it preloaded, some loaded on demand) and ends up in properties of these globally available objects:
 * for MediaWiki core,
 * for jQuery,
 * for OOjs.

Some commonly accessed properties of  include ,  ,  ,  ,  , and. is the namespace of OOUI. See ResourceLoader/Core modules for more details.

Development and testing
The following development environments can be used to develop and test your script.

Basic

 * Using the preview button: You can edit your script directly on your /common.js page, then click [Show preview] and the new code is executed right away on the preview page.
 * Saving it: If required elements are missing on the preview page (for example, your script does something on history pages), you will have to save the script in order to test it. However, it's not convenient and creates unnecessary entries in the page history.
 * Execute it in your browser's JavaScript console: All modern browsers come with a JavaScript console and other development tools. You can type or paste and execute your code there; script errors and warnings will also be shown there. How to open the console depends on your browser:
 * In Google Chrome and Edge – press
 * In Firefox – press
 * In Safari – press
 * You may need to click the Console tab if a different pane is currently open.

Loading it from a localhost web server
The best and most recommended way to load a JavaScript file during development is from your local web server (see below for an easy way to install a web server). Put this string in your /common.js:

In some environment, you need write this like :

Then run any web server on your computer and create the wikipediatest.js file in the appropriate folder. The code inside this file will be executed as if it was inside your personal script.

You can edit your wikipediatest.js file with any text editor, perhaps with syntax highlighting and other convenient features, save the file and simply reload any Wikipedia page to see the results. (You don't need to wait, and if your web server is nice or you set it right, you don't even need to bypass your browser cache.)

Most modern code editors and IDEs allow you to set up a localhost server – eg. use atom-live-server in Atom, and Live Server in VS Code. WebStorm and PhpStorm have the feature built in, without requiring an extension. You can also use a third party program such as Node.js's  command (video tutorial), or XAMPP. If you have Python installed, you can run  from command-line.

On Windows, you could also use for example TinyWeb which is less than 100 kbyte on disk and doesn't require installation. Save and unzip tinyweb.zip for example into c:\Program Files\Tinyweb, create a shortcut to tiny.exe , and add an argument in shortcut properties — path to your folder with wikipediatest.js and any file index.html (required). Start TinyWeb with this shortcut; unload it with Task Manager.

Note that this method doesn't work in Opera 9.50 (and later) due to added security restrictions, see Opera 9.50 for Windows changelog: "Local servers can use remote resources, but not vice versa". In Chrome, it may be necessary to enable SSL, otherwise the script will refuse to load.

Browser-specific
Some browsers allow you to automatically execute your JavaScript code on specific web pages. This way you don't have to be logged in to Wikipedia. One example is Tampermonkey. However, making user scripts work with one of these extensions might require some modifications to the script code.

Running pieces of code
You can run pieces of code on already loaded pages via the JavaScript console. See the guide for doing this in Chrome. It works similarly in most other browsers. In addition, Chromium-based browsers have a snippets feature where short pieces of JavaScript code can be saved and debugged.

Publishing
Once you have finished the user script code, you can save it as a page so that others can import it. By convention, scripts are in your userspace and have titles ending in ".js", for example "User:YourUsernameHere/MyCoolScript.js". Others can then install the new script.

Text editors
You can use anything from a simple text editor, to a more feature-packed code editor or IDE. Here are some features we recommend:


 * 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 globally available objects of MediaWiki, jQuery, OOjs, and OOUI.
 * Show the list of all functions and quickly jump to any function

Here are some recommended editors, by operating system.


 * Windows
 * VS Code (cross-platform)
 * Notepad++
 * Mac OS X
 * Xcode
 * JEdit (cross-platform)
 * Komodo Edit (cross-platform)
 * Aptana Studio (cross-platform)
 * TextMate (not free)
 * Coda (not free)
 * PhpStorm (not free, cross-platform, a free license for MediaWiki Developers is also available )
 * Linux
 * gedit (may come with Linux)
 * Kate (may come with Linux)

JavaScript Debuggers
These are typically built into browsers, in their DevTools window. Debuggers allow you to step debug (go through your JavaScript code line-by-line, hover over variables to see their values, etc.)


 * Firefox - use Tools → JavaScript Console which shows all JavaScript and CSS errors.
 * Chrome and Edge - use Tools → Developer Tools.
 * Safari - Safari → Preferences → Advanced and enable the "Show Develop menu in menu bar" option. Then use Develop → Show Web Inspector to open up the development tools.
 * Opera - use Tools → Advanced → Error Console which shows all JavaScript and CSS errors.

Running code on page load
The personal  module (built from /common.js, /common.css and optionally the skin-specific files for the current skin; see above) and gadgets are loaded on all pages. Most scripts will want to manipulate elements on the page; to do so the page needs to be ready (which may not be the case at the time the modules are loaded). We can defer execution of code by using a special function.

One option is  from jQuery.

Since the function is called only once, many users prefer to shorten this code with an anonymous function:

 Note:  and   are the same object; choosing between them is purely a matter of opinion.

Many scripts use this function simply to add some script interface, such as a link in a portlet. Then the main part of the code is executed after the user clicks on that link.

However, if your code works with the content part of the page (the  element), you should use the   hook instead. This way your code will successfully reprocess the page when it is updated asynchronously and the hook is fired again. There are plenty of tools which do so, ranging from edit preview to watchlist autoupdate.

Be sure to only work with the descendants of the  element that your handler function takes and not the whole page. Otherwise, you may end up running the same code for the same elements many times. Note that the  hook may be fired really many times.

Be cautious about what comes in the  argument of the handler function. You shouldn't assume it's the  element. It can be a small portion of the page, e.g. when it is previewed.

Code that works with page content and avoids the aforementioned pitfalls may look like this:

If your code works with page content and adds event handlers to DOM elements, then, instead of hooking to  and looking for elements to attach event listeners to when it is fired, you may attach one event listener to an element outside of the content area or the whole   but filter events by a selector (see jQuery's documentation). That is, instead of writing  you can write.

Finding elements
Every HTML element is a node in a DOM model which allows scripts to access the element, for example, on the following HTML page.

We can find element :
 * Using its :
 * In the array of all elements with the same :
 * Using an element next to it:
 * As a child of its parent:
 * As a form element, using :

'' This example on jsFiddle

The [//api.jquery.com jQuery API reference] is an excellent source for documentation.

Checking the current page
Many scripts are supposed to work only on some pages. You can check:


 * The page type
 * wg (Wikimedia global) variables; many of them have the same meaning as Magic words


 * Presence of elements (only in second and third parts of the script)

Portlets (menus and tabs)
Portlets are MediaWiki's name for groups of links located in the topbar and sidebar. Here is a diagram of portlet ID's.



List of portlets (portlet types)

 * Top
 * p-personal - The links at the very top right of the page. "personal" stands for "personal tools".
 * p-namespaces - The tabs on the left that never collapse. Not recommended, not much space. The article and talk tabs are located here.
 * p-views - The tabs in the middle that never collapse. Not recommended, not much space. The favorite page star tab is located here.
 * p-cactions - The items in the "More" tab's dropdown menu. "cactions" stands for "content actions".
 * p-search - Adding things here will mess up the appearance of the search box. Not recommended.
 * Left
 * p-logo - Adding things here will mess up the appearance of the logo. Not recommended.
 * p-navigation
 * p-interaction - Has the title "Contribute".
 * p-tb - Has the title "Tools". TB stands for toolbox.
 * p-coll-print_export - Has the title "Print/export". Not a good place to add things, since this should just be for printing and exporting.
 * p-wikibase-otherprojects - Has the title "In other projects". Not a good place to add things, since this should just be for links to other projects such as Wikisource, Wikibooks, etc.
 * p-lang - Has the title "Languages". Not a good place to add things, since this should just be for languages.

Adding elements
There is a special function in,   that simplifies the process of adding your own links to portlets. The advantage of using this function is that your code should work across all skins, and not break when these skins change their HTML. Its parameters, in order:


 * – ID of the target portlet
 * – link URL
 * Set to  if you don't need to open a page and want to use a JavaScript listener instead.
 * – human-readable link text
 * (optional) – unique ID of the item
 * Use a prefix such as ca-, pt-, n-, or t- – for consistency with other links in the group of chosen.
 * (optional) – helpful text appearing on mouse hover
 * (optional) – keyboard shortcut key
 * Set to  if you don't need it.
 * Use  in the console to see if 'x' is already used.
 * (optional) – element that this will be added in front of

Or you can use JQuery. Simply attach it in another place with,  ,  , or. . Warning: This is very fragile. You may get it working on a couple skins, but a couple other skins may look broken.

Removing elements
To hide an element, you can use JQuery's [//api.jquery.com/hide/ ] function.

Or you can do it by placing code in common.css:

Adding menus
You can add menus using  (see documentation). The menu will not show up until you put a portletLink in it. If you add a menu adjacent to #p-cactions, it will be a dropdown menu in the Vector and Vector 2022 skins, with the correct dropdown HTML added for you.

Textarea with article wikicode
The most important element on the edit page is a with the article text inside. You can reference it with

You can manipulate it using the jquery.textSelection ResourceLoader module.

Or you can grab 's text, create a string, modify it, then write it back. Note; other editing tools might not recognise your changes or cause conflicts if you use this methodology instead of the textSelection api.

Editing toolbar
WikiEditor is now the default toolbar when editing the source code of articles, but some users are still using the original toolbar. You can turn on and off WikiEditor by checking and unchecking the "Enable the editing toolbar" check box in your preferences.

Edittools
There is another edit panel under textarea. Usually it's generated from MediaWiki:Edittools by Extension:CharInsert and consists of a lot of JavaScript links. In the English Wikipedia, this approach was replaced by MediaWiki:Gadget-charinsert.js and MediaWiki:Gadget-charinsert-core.js.

Doing something after another user script
Sometimes you may want to add or remove something from the DOM, but another user script edits the same area of the DOM. It can be random which user script finishes first, creating a race condition.

One way to coordinate this is use the mw.hook interface. Perhaps the other script sends a  event when it's done, or can be modified to do so (or you can ask the maintainer).

Another way to avoid this is to use the  or   events to listen for when the other user script is finished, ensuring that your user script executes last.

User settings
If you want your users to be able to manually set configuration variables, one way to do this is to have them place  in their common.js file. Then within your user script, you can read this value with.

Notice that "scriptName" is one of the pieces of the variable name. This is important to help make sure the variable is unique.

Do not use  in the common.js file. If the user forgets the setting, you may get undeclared variable errors.

If you want your user script to write and save configuration settings while it is running, you may want to have it write to its own .js file in the user's userspace. See twinkleoptions.js or redwarnConfig.js for examples.

&lt;nowiki&gt; tags
You may want to place the following code at the top and bottom of your user script, in a comment. This will help prevent bugs, such as  turning into your hard-coded signature when you save the page.

Function scope
Don't declare named functions in the global namespace. For example, this is bad:

What if another of your user scripts also declares a  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. JavaScript allows nested functions.

Ajax
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.

While programming AJAX can be complex, libraries of functions can make it much easier. Since the 1.16 release, MediaWiki comes with the jQuery library, which provides a convenient framework for easily making Ajax requests.

Common problems

 * AJAX programmers commonly run into problems if they don't 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 . This occurs because the script continued even though the query wasn't finished.  To correct the problem, you need to use 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 very easy to do.
 * 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 provides some modules with helper functions which facilitate the use of its API. The main modules available are If your script makes use any method or code provided by these modules, remember to indicate the dependencies with mw.loader.using or, in case of gadgets, on its definition at MediaWiki:Gadgets-definition.
 * mediawiki.api

This API has several advantages especially when dealing with POST requests. It provides automatic token refresh and retry, handles various error situations and does parameter request building for several common use cases like rolling back a revision.

Be sure to follow the 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.

Using module
Note: make sure to add  to your dependencies!

Edit a page and other common actions
Scripts can perform common actions (like editing, protection, blocking, deletion, etc.) through the [/w/api.php API]. These actions require an edit token, which is 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.)

The code below shows how to edit a page, but it can easily be adapted to other actions by reading the [/w/api.php API documentation].

Using module
Note: make sure to add  to your dependencies!

Load JavaScript from Wiki page
Security warning: Do not load Wikipedia pages that do not end in .js into your script using this method, because anybody can edit those pages.

Load JSON from Wiki page
JSON is useful when you want to import complex data into your script. For example, maybe you have a bot that publishes certain data to a Wiki page regularly, and you want your script to read that data.

Careful with. Set it to  for normal Wiki pages, and   for pages where a template editor or admin has set the Content Model to JSON.

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 in your /common.css, but it is slow and messy.

Instead, 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 very top of your /common.css: Note! Such  statements must come before any other declarations in your CSS. But there can be  above them.

An alternative way is to put this line in your Javascript file instead:

Publishing a CSS file
Once you have finished the CSS code, you either need to paste it into your /vector.css if it is only for personal use. Or if it is for use by others then you should upload it to for instance User:Yourname/yourscript.css. Then other users can import it by putting the following line in their /common.js file. Note, that is in their ".js", not their ".css".

If the CSS should be used together with a user script written in JavaScript then you can make it easy for the users. Simply put the line above in the JavaScript code for your user script, then the users only need to "install" your JavaScript.

For completeness, in case someone wonders, users can import your User:Yourname/yourscript.css from their /common.css too. This of course has the advantage that it works even if the user has JavaScript disabled. Although it takes this slightly complex line of code: