විකිපීඩියා:User scripts/Guide
PrerequisitesTo 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 Wikipedia:User scripts#How do you install user scripts?). Forking an existing scriptStarting 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",[n. 1] of your user page. Then, install the new page like a normal user script. Writing a script from scratchWhile 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 worldTo make a Hello world program, insert this code into your User:YourUserName/common.js file. importScript('User:YourUserName/hello-world.js');
Next, create the page User:YourUserName/hello-world.js, and insert this code. $('#bodyContent').prepend('<p>Hello world!</p>');
This will write "Hello world!" on every page, below the title, until you remove the code. This uses JQuery, although you could also write this in pure JavaScript. Your first scriptWe 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 // Qwikify
$(document).ready( function () {
MODULE_CODE;
} );
In Altogether, your new function should look like this: // Make sure the utilities module is loaded (will only load if not already)
mw.loader.using( 'mediawiki.util', function () {
// Wait for the page to be parsed
$( document ).ready( function () {
//see below "Portlets" subsection
var link = mw.util.addPortletLink( 'p-cactions', '#', 'Wikify', 'ca-wikify', 'Mark for wikification');
$( link ).click( function ( event ) {
event.preventDefault();
doQwikify();
} );
} );
} );
Now, we must write our actual document.editform.wpTextbox1.value = "{" + "{wikify}}\n\n" + document.editform.wpTextbox1.value;
(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 function doQwikify() {
document.editform.wpTextbox1.value = "{" + "{wikify}}\n\n" + document.editform.wpTextbox1.value;
document.editform.submit();
}
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![1] On load/document ready functionThe personal "user" module (built from /common.js, /common.css and optionally the skin-specific files for the current skin) 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. Most commonly // Define our main function
function myScript() {
// ... code ...
};
// Schedule it to run after the HTML page is parsed
$( document ).ready( myScript );
// This shorthand is also valid
jQuery( myScript );
Since the function is called only once, many users prefer to shorten this code with an anonymous function: $( document ).ready( function () {
// ... code ...
} );
// Or
jQuery( function () {
// ... code ...
} );
Note: 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. Built-in scriptsAll Wikipedia pages include some built-in MediaWiki JavaScript code, with variables and functions that can be used in user scripts. The specific code depends on the viewed page and current users, for more details see Wikipedia:Catalogue of CSS classes#Stylesheets and JavaScript. Of most interest are:
Development and testingThe following development environments can be used to develop and test your script. Basic
Loading it from a localhost web serverThe 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: mw.loader.load( 'https://localhost/wikipediatest.js' );
In some environment, you need write this like[2]: mw.loader.load( 'http://127.0.0.1/wikipediatest.js' );
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 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-specificSome 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 codeYou 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. PublishingOnce 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",[n. 1] for example "User:YourUsernameHere/MyCoolScript.js". Others can then install the new script. Text editors and debuggingText editorsYou can use anything from a simple text editor, to a more feature-packed code editor or IDE. Here are some features we recommend:
Here are some recommended editors, by operating system.
JavaScript DebuggersThese 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.)
Basic techniquesFinding elementsEvery HTML element is a node in a DOM model which allows scripts to access the element, for example, on the following HTML page. <form name="frmname" id="frmid">
<textarea name="txtname" id="txtid"></textarea>
<input id="neighbor" />
</form>
We can find element textarea:
The jQuery API reference is an excellent source for documentation. Checking the current pageMany scripts are supposed to work only on some pages. You can check:
if ( mw.config.get( 'wgAction' ) === 'history' ) { // Continue only on history pages.
if ( mw.config.get( 'wgCanonicalNamespace' ) === 'User_talk') { // Continue only on User_talk pages.
if ( mw.config.get( 'wgPageName' ) === 'Article_name' ) { // Continue only for the article "Article name".
function func_start() {
if ( $( '#editForm' ).length == 0 ) return; //No edit form ? exit
// …
Portlets (menus and tabs)ප්රධාන පිටුව: Help:Customizing toolbars 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 structure<div id="p-myname" class="portlet">
<h5>Header</h5>
<div class="body">
<ul>
<li id="…"> <a …> //Links
<li id="…"> <a …>
… …
Adding elementsThere is a special function in mediawiki.util.js 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.
); // Several examples of portlet links
// Adds a link to your js file to the toolbox. tb = toolbox
mw.util.addPortletLink ( 'p-tb', mw.util.getUrl( 'Special:MyPage/common.js' ), 'My JS', 'pt-myvector', 'Visit your js file');
// Add a link to the edit page for your Notes in your personal links
// Note: We assume that short/pretty URLs are in use with ?action, ideally you would check for that.
mw.util.addPortletLink ( 'p-personal', mw.util.getUrl( 'Special:MyPage/Notes' ) + '?action=edit', 'My notes', 'pt-mynotes', 'Edit your personal notes' );
// Adds a link to prefix index for the current page to the toolbox
mw.util.addPortletLink ( 'p-tb', mw.util.getUrl( 'Special:Prefixindex/' + mw.config.get( 'wgPageName' ) ), 'Prefixindex', 'tb-prefixindex');
// Adds a link to logs for your account
mw.util.addPortletLink ( 'p-personal', mw.util.getUrl( 'Special:Log/' + mw.config.get( 'wgUserName' ) ), 'My logs', 'pt-mylogs');
Or you can use JQuery. Simply attach it in another place with // Add a clickable button on the edit article page, above the edit summary.
$('.editOptions').prepend('<button type="button" id="my-custom-button">Do Things</button>');
// Add a listener to your button, that does something when it is clicked.
$('#my-custom-button').click(function(e) {
// do things
});
Removing elementsTo hide an element, you can use JQuery's // Example: remove special characters toolbar from edit page
$( '#editpage-specialchars' ).hide();
// Or modify the CSS directly
$( '#editpage-specialchars' ).css( 'display', 'none' );
Or you can do it by placing code in common.css: #editpage-specialchars {
display:none;
}
EditingTextarea with article wikicodeThe most important element on the edit page is a <textarea> with the article text inside. You can reference it with var $textbox = $( '#wpTextbox1' );
You can manipulate it using the jquery.textSelection ResourceLoader module. var $textbox = $( '#wpTextbox1' );
$textbox.textSelection( 'setContents', 'This is bold!' );
$textbox.textSelection( 'setSelection', { start: 8, end: 12 } );
$textbox.textSelection( 'encapsulateSelection', { pre: '<b>', post: '</b>' } );
// Result: Textbox contains 'This is <b>bold</b>!', with cursor before the '!'
Or you can grab // Get value.
let value = $('#wpTextbox1').val();
// Your code goes here. Do things to value. RegEx, .replace(), concatenate, etc.
// Then write it back.
$('#wpTextbox1').val(value);
Editing toolbarWikiEditor 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.[n. 2][n. 3] EdittoolsThere 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 scriptSometimes 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's done, or can be modified to do so (or you can ask the maintainer). Another way to avoid this is to use the $('body').on('DOMNodeInserted', '.preferences-link.link', function() {
// do things
}
User settingsIf you want your users to be able to manually set configuration variables, one way to do this is to have them place 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 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. Preventing bugs<nowiki> tagsYou 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 //<nowiki>
Your code here.
//</nowiki>
Function scopeDon't declare named functions in the global namespace. For example, this is bad: function submitEdit() {/* do stuff */}
$(function{/* main code here */});
What if another of your user scripts also declares a $(function{
function submitEdit() {/* do stuff */}
/* main code here */
});
AjaxAJAX (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
Basic examplesMediaWiki 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. 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 contentFetching a page content can be done using GET. $.ajax({
url: mw.util.getUrl( 'Wikipedia:Sandbox' )
})
.then(function( data ) {
alert( 'The remote page contains:\n' + data );
})
.catch(function() {
alert( 'The ajax request failed.' );
});
Get the wikitext of a pageUsing module |
Portal di Ensiklopedia Dunia