Wikipedia / Wikipedia:User scripts/Guide
Wikipedia / Wikipedia:User scripts/Guide
Prerequisites
To write user scripts, you will 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 ).
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
Although 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 and 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 the following 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, a JavaScript library that specializes in manipulating HTML. $ is a JQuery function that lets us target the HTML element we want. #bodyContent is a string in CSS selector syntax, and means target the HTML element with property id="bodyContent" . prepend is a JQuery function that inserts HTML code as a child of the #bodyContent element. is the HTML code to be inserted.
Your first script
We will be writing a user script by modifying your common.js. For the purpose of this tutorial, we will write a simple user script which adds the maintenance template to the top of an article when you click a link called "Add notability tag" in the "More" menu. Visit a page and click "edit source". Now let's start writing code. Let's start with a function that waits for the page to fully load, then executes something inside it:
In the TODO, we want to add the "Add notability tag" menu item, so we will use the addPortletLink() function (requiring the mediawiki.util module). Replace the TODO with a call to this function. Then we will bind an event handler so that when this link is clicked, we will call another function named addTag() that will actually execute the code.
Lastly, we use jQuery's .click() to listen for clicks on this link, and when that happens, execute a function. After we call addTag(), it says event.preventDefault(). Since we clicked on a link, we need to tell the browser to prevent its default behavior (going to the URL, '#'). We want the page to stay right where it is 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 addTag() function. It will edit the page's wikicode text box, so we need to get the HTML IDs of that and its form. Viewing the source of the page shows that HTML form has id="editform" and the textarea has id="wpTextbox1", meaning we can target these element with the jQuery code $( '#wpTextbox1' ) and $( '#editform' ). We can set and retrieve a value from this fancy text box using jQuery's .textSelection() function. To add (and two empty lines), we 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, jQuery has a built-in function just for this named submit(). To submit our editing form, use $( '#editform' ).submit();. Your code should now look something like this:
And that's it! Combine it all together and it should look like this:
Save this to your User:YourUserName/common.js page. Then go visit a page such as the Sandbox, click on "Edit Source", go into the "More" menu, click "Add notability tag", and watch the user script add the maintenance tag for you.
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 ($(), importScript(), mw.util). 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:
Some commonly accessed properties of mw include mw.config, mw.user.options, mw.util, mw.Title, mw.loader, and mw.hook. OO.ui is the namespace of OOUI. See mw: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 is 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 environments, you need to write this as:
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 do not need to wait, and if your web server is nice or you set it right, you do not even need to bypass your browser cache.)
Most modern code editors and IDEs allow you to set up a localhost server –eg. 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 npx http-server command (video tutorial), or XAMPP.
If you have Python installed, you can run python -m http.server from command-line from the folder your script is in.
On Windows, you could also use for example TinyWeb, which is less than 100kilobytes on disk and does not require installation. Save and unzip tinyweb.zip to a safe location, for example into c:\Program Files\Tinyweb. Then 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 do not 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 and debugging
Text editors
You can use anything from a simple text editor, to a more feature-packed code editor or IDE. Here are some recommended editors, and the operating systems they're available for.
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 showing all JavaScript and CSS errors.
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 showing all JavaScript and CSS errors.
Basic techniques
Running code on page load
The personal user 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 (it may not be the case at the time the modules are loaded). We can defer execution of code by using a special function.
$(document).ready(...)
One option is .ready() from jQuery.
Since the function is called only once, many users prefer to shorten this code with an anonymous function:
Note: $ and jQuery 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.
mw.hook('wikipage.content').add(...)
However, if your code works with the content part of the page (the #mw-content-text element), you should use the 'wikipage.content' 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 that do so, ranging from edit preview to watchlist autoupdate.
Be sure to only work with the descendants of the $content 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 'wikipage.content' hook may be fired really many times.
Be cautious about what comes in the $content argument of the handler function. You should not assume it is the #mw-content-text 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 'wikipage.content' 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 document 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 allowing scripts to access the element, for example, on the following HTML page.
We can find element textarea:
Using its id:
In the array of all elements with the same tag:
Using an element next to it:
As a child of its parent:
As a form element, using name:
The 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 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 mediawiki.util, mw.util.addPortletLink() 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:
portletId – ID of the target portlet
href – link URL
Set to '#' if you do not need to open a page and want to use a JavaScript listener instead.
text – human-readable link text
id (optional) – unique ID of the item
Use a prefix such as , , , or – for consistency with other links in the group of chosen portletId.
tooltip (optional) – helpful text appearing on mouse hover
accesskey (optional) – keyboard shortcut key
Set to null if you do not need it.
Use $( '[accesskey=x]' ) in the console to see if 'x' is already used.
nextNode (optional) – element that this will be added in front of
Or you can use JQuery. Simply attach it in another place with .append(), .prepend(), .before(), or .after(). https://www.w3schools.com/jquery/jquery_dom_add.asphttps://javascript.info/article/modifying-document/before-prepend-append-after.svg. Warning: This is 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 function.
Or you can do it by placing code in common.css:
Adding menus
You can add menus using mw.util.addPortlet() (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.
Editing
Textarea with article wikicode
The most important element on the edit page is a <textarea> with the article text inside. You can reference it with
You can manipulate it using the jquery.textSelection ResourceLoader module.
Or you can grab <textbox>'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 is 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.
Automatic and semi-automatic editing
You can automate the editing of a page using the following code template:
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 wikipage.content 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 MutationObserver.
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 window.scriptNameSettingName = 'value here'; in their common.js file. Then within your user script, you can read this value with if ( window.scriptNameSettingName == 'value here' ).
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 let scriptNameSettingName = 'value here'; 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 as 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.
Preventing bugs
<nowiki> 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.
If you need to print nowiki or /nowiki tags within your user script, use a trick such as const tag = '</' + 'nowiki>'; to keep from messing up the nowiki tag on line 1 and on the last line.
Function scope
Do not declare named functions in the global namespace. For example, this is bad:
What if another of your user scripts also declares a function? 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 . 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. This is great for API requests. We do not have access to the SQL database in front end code, so the MediaWiki action API (or one of the other APIs) is the main way we retrieve data.
Basic examples
mediawiki.api
MediaWiki provides some modules with helper functions facilitating 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.
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.
Get the wikitext of a page
Using module mediawiki.api
Note: make sure to add mediawiki.api to your dependencies!
Using jQuery $.getJSON
Using jQuery $.ajax
Fetching a page content can be done using jQuery $.ajax, which does an HTTP GET request.
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, 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 mediawiki.api
Note: make sure to add mediawiki.api to your dependencies!
Using plain jQuery
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 ctype. Set it to raw for normal Wiki pages, and application/json 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 via editing your User:YourUserName/common.css page.
Loading a localhost file
For local development, 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 /common.css: Note! Such @import statements must come before any other declarations in your CSS, except comments.
An alternative way is to put this line in your /common.js 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:
See also
Notes
References