Gadget kitchen/pt-br: Difference between revisions
Created page with "Se estiver executando sua própria cópia do MediaWiki, $1 precisa estar ativado para que scripts de usuário funcionem, e a extensão $2 precisa ser instalada para possibili..." |
Updating to match new version of source page |
||
(52 intermediate revisions by 3 users not shown) | |||
Line 3: | Line 3: | ||
Este é um tutorial de como pode escrever e utilizar ''gadgets'' e ''scripts'' pessoais em JavaScript. |
Este é um tutorial de como pode escrever e utilizar ''gadgets'' e ''scripts'' pessoais em JavaScript. |
||
<span id="What_are_user_scripts_and_gadgets?"></span> |
|||
== O que são ''scripts'' pessoais e ''gadgets''? == |
== O que são ''scripts'' pessoais e ''gadgets''? == |
||
O MediaWiki permite que todos escrevam código [[Special:MyLanguage/Learning JavaScript|JavaScript]] público para alterar imediatamente o comportamento do ''software''. |
O MediaWiki permite que todos escrevam código [[Special:MyLanguage/Learning JavaScript|JavaScript]] público para alterar imediatamente o comportamento do ''software''. |
||
Este código pode ser compartilhado com outros usuários. |
Este código pode ser compartilhado com outros usuários. |
||
Este código localiza-se em páginas wikis. |
Este código localiza-se em páginas wikis. |
||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
* A '''user script''' can be edited by the original author (if it is stored in the <code>User:</code> namespace) and by anyone with the "edituserjs" user-right (usually just interface administrators). The code is usually hosted on a sub page of [[Special:MyPage|your user page]]. Examples include: [[XTools/ArticleInfo.js]] and [[m:User:Hoo man/useful links.js]]. User scripts are similar to the [[Special:MyLanguage/Manual:Interface/JavaScript#Personal_scripts|personal JavaScript]] pages such as [[Special:MyPage/common.js]], but they allow single code chunks to be shared with other users. |
|||
* A '''user script''' can be edited by the original author (if it is stored in the <code>User:</code> namespace) and by anyone with the "edituserjs" user right (usually just interface administrators). |
|||
</div> <span lang="en" dir="ltr" class="mw-content-ltr">The code is usually hosted on a subpage of [[Special:MyPage|your user page]].</span> <span lang="en" dir="ltr" class="mw-content-ltr">Examples include: [[XTools/ArticleInfo.js]] and [[m:User:Hoo man/useful links.js]].</span> <span lang="en" dir="ltr" class="mw-content-ltr">User scripts are similar to the [[Special:MyLanguage/Manual:Interface/JavaScript#Personal_scripts|personal JavaScript]] pages such as [[Special:MyPage/common.js]], but they allow single code chunks to be shared with other users.</span> |
|||
* Um '''''gadget''''' é um ''script'' pessoal que foi "promovido" por um [[meta:Special:MyLanguage/Interface administrators|administrador de interface]], adicionando-o à página [[MediaWiki:Gadgets-definition]]. Usuários registrados podem ativar ''gadgets'' na aba [['Special:Preferences#mw-prefsection-gadgets|''"Gadgets"'']] de suas preferências de usuário. Os ''gadgets'' são criados e gerenciados por administradores de interface. |
* Um '''''gadget''''' é um ''script'' pessoal que foi "promovido" por um [[meta:Special:MyLanguage/Interface administrators|administrador de interface]], adicionando-o à página [[MediaWiki:Gadgets-definition]]. Usuários registrados podem ativar ''gadgets'' na aba [['Special:Preferences#mw-prefsection-gadgets|''"Gadgets"'']] de suas preferências de usuário. Os ''gadgets'' são criados e gerenciados por administradores de interface. |
||
* Para completude: Também há o '''siteJS''' localizado na página [[MediaWiki:Common.js]]. O JavaScript naquela página afeta todos os usuários e é executado automaticamente tanto para usuários registrados quanto para não registrados. Interface administrators can edit |
* Para completude: <span class="mw-translate-fuzzy">Também há o '''siteJS''' localizado na página [[MediaWiki:Common.js]].</span> <span class="mw-translate-fuzzy">O JavaScript naquela página afeta todos os usuários e é executado automaticamente tanto para usuários registrados quanto para não registrados.</span> <span lang="en" dir="ltr" class="mw-content-ltr">Interface administrators can edit them.</span> <span lang="en" dir="ltr" class="mw-content-ltr">Read [[Special:MyLanguage/Manual:Interface/JavaScript|Manual:Interface/JavaScript]] for detailed information.</span> |
||
Se estiver executando sua própria cópia do MediaWiki, {{wg|AllowUserJs}} precisa estar ativado para que scripts de usuário funcionem, e a extensão {{ll|Extension:Gadgets |
<span class="mw-translate-fuzzy">Se estiver executando sua própria cópia do MediaWiki, {{wg|AllowUserJs}} precisa estar ativado para que scripts de usuário funcionem, e a extensão {{ll|Extension:Gadgets|Gadgets}} precisa ser instalada para possibilitar a promoção de scripts individuais para o ''status'' de ''gadget''.</span> |
||
Para uma experiência de desenvolvimento melhor, certifique-se de que a extensão {{ll|Extension:CodeEditor|nsp=0}} esteja instalada em sua wiki. |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
== Write your first user script == |
== Write your first user script == |
||
</div> |
|||
In this section, you create an example user script which calculates the estimated reading time of a wiki page. |
<span lang="en" dir="ltr" class="mw-content-ltr">In this section, you create an example user script which calculates the estimated reading time of a wiki page.</span> |
||
# Ensure you are [[Special:Userlogin|logged in]]. |
# <span lang="en" dir="ltr" class="mw-content-ltr">Ensure you are [[Special:Userlogin|logged in]].</span> |
||
# Visit [[Special:MyPage/common.js]]. This page holds your [[Special:MyLanguage/Manual:Interface/JavaScript#Personal_scripts|personal JavaScript]] that is loaded on every page view (except for Special:Preferences). |
# <span lang="en" dir="ltr" class="mw-content-ltr">Visit [[Special:MyPage/common.js]].</span> <span lang="en" dir="ltr" class="mw-content-ltr">This page holds your [[Special:MyLanguage/Manual:Interface/JavaScript#Personal_scripts|personal JavaScript]] that is loaded on every page view (except for Special:Preferences).</span> |
||
# Either create the page or edit the page if it already exists. |
# <span lang="en" dir="ltr" class="mw-content-ltr">Either create the page or edit the page if it already exists.</span> |
||
# Copy the following six lines and paste these lines into the page: |
# <span lang="en" dir="ltr" class="mw-content-ltr">Copy the following six lines and paste these lines into the page:</span> |
||
#:<syntaxhighlight lang="javascript"> |
|||
var numWords = $("#mw-content-text > div").text().split(" ").length; |
var numWords = $("#mw-content-text > div").text().split(" ").length; |
||
var headerWords = $("h1").text().split(" ").length; |
var headerWords = $("h1").text().split(" ").length; |
||
Line 30: | Line 33: | ||
var header = $("h1").text(); |
var header = $("h1").text(); |
||
$("h1").text(header + " (it will take you " + timeInMinutes + " minutes to read this page)"); |
$("h1").text(header + " (it will take you " + timeInMinutes + " minutes to read this page)"); |
||
</syntaxhighlight> |
|||
</source> |
|||
# <span lang="en" dir="ltr" class="mw-content-ltr">Click "{{int|publishchanges}}".</span> |
|||
# Click "Publish changes". |
|||
# Go to any page. Look at the title. |
# <span lang="en" dir="ltr" class="mw-content-ltr">Go to any page. Look at the title.</span> |
||
This example user script is taken from {{ll|ChickTech High School Kickoff 2017/Tasks}}. |
<span lang="en" dir="ltr" class="mw-content-ltr">This example user script is taken from {{ll|ChickTech High School Kickoff 2017/Tasks}}.</span> |
||
<span lang="en" dir="ltr" class="mw-content-ltr">There are more examples for simple user scripts on that page.</span> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
In general, check out [[Special:MyLanguage/Manual:Coding conventions/JavaScript|the JavaScript coding conventions]] to write JavaScript that complies with MediaWiki's style. |
|||
== A more complex user script example == |
|||
</div> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
Check out '''[[MediaWiki:Tutorial-QuickRC.js]]''' which uses ''mw.loader, mw.util, mw.html, mw.user'' from ResourceLoader, the MediaWiki Action API, a jQuery UI dialog, jQuery AJAX, and jQuery event binding. |
|||
</div> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
Copy and paste the contents of [[MediaWiki:Tutorial-QuickRC.js]] into your [[Special:MyPage/common.js]]. |
|||
</div> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
The result should be the same as above, but now you can modify the script, play with it, and replace it with something else entirely. |
|||
</div> |
|||
{{note|1=<span lang="en" dir="ltr" class="mw-content-ltr">Clicking "Preview" (or using the keyboard shortcut, typically {{Key press|Shift|Alt|P}}) in the editor will also execute the latest version of the script. This is a good way to iterate without saving the page. Remember, nothing is saved until you press "Publish page".</span>}} |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
== Load an existing user script == |
|||
</div> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">In the previous section, you copied the content of a user script.</span> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">In this section, you will load the existing script [[MediaWiki:Tutorial-QuickRC.js]] instead.</span> |
|||
# <span lang="en" dir="ltr" class="mw-content-ltr">Ensure you are [[Special:Userlogin|logged in]].</span> |
|||
# <span lang="en" dir="ltr" class="mw-content-ltr">Visit [[Special:MyPage/common.js]].</span> <span lang="en" dir="ltr" class="mw-content-ltr">This page holds your [[Special:MyLanguage/Manual:Interface/JavaScript#Personal_scripts|personal JavaScript]] that is loaded on every page view (except for Special:Preferences).</span> |
|||
# <span lang="en" dir="ltr" class="mw-content-ltr">Either create the page or edit the page if it already exists.</span> |
|||
# <span lang="en" dir="ltr" class="mw-content-ltr">Copy the following text and paste it into the page:</span> <syntaxhighlight lang="js">mw.loader.load('//www.mediawiki.org/w/index.php?title=MediaWiki:Tutorial-QuickRC.js&action=raw&ctype=text/javascript');</syntaxhighlight> |
|||
# <span lang="en" dir="ltr" class="mw-content-ltr">Click "Publish changes". You should now have a link in the "Tools" section called "Quick changelog".</span> |
|||
# <span lang="en" dir="ltr" class="mw-content-ltr">Click "Quick changelog". You get a pop-up window.</span> <span lang="en" dir="ltr" class="mw-content-ltr">It shows you a subset of the [[Special:RecentChanges|recent changes]] on this website.</span> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
=== Use a script on another Wikimedia wiki === |
|||
</div> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
If you want to use a script on another Wikimedia website (for example English Wikipedia instead of MediaWiki.org), you perform the same steps as above: you tell ResourceLoader to load your code. Visit your [[w:Special:MyPage/common.js|common.js]] on English Wikipedia, and add the following: |
|||
</div> |
|||
<syntaxhighlight lang="js"> |
|||
mw.loader.load("//www.mediawiki.org/w/index.php?title=MediaWiki:Tutorial-QuickRC.js&action=raw&ctype=text/javascript"); |
|||
</syntaxhighlight> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">You can also load the user script which you just created above, by changing <code>MediaWiki:Tutorial-QuickRC.js</code> in the previous line to <code>User:''YourName''/''YourScript''.js</code> (replace <code>''YourName''</code> and <code>''YourScript''</code> accordingly).</span> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">This first requires that you do not store the code of your user script in [[Special:MyPage/common.js]] itself but instead in a separate sub page of [[Special:MyPage|your user page]].</span> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
This also helps to [[mw:Special:MyLanguage/ResourceLoader/Migration guide (users)#Keep gadgets central|keep code in one single place, so you have to update code in only one place]]. |
|||
</div> |
|||
<span id="Developing_user_scripts_and_gadgets"></span> |
|||
==Desenvolvimento de ''scripts'' pessoais e ''gadgets''== |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
==Developing user scripts and gadgets== |
|||
This section lists resources which are either needed or helpful for non-simple user scripts. |
This section lists resources which are either needed or helpful for non-simple user scripts. |
||
</div> |
|||
=== ResourceLoader === |
=== ResourceLoader === |
||
<span class="mw-translate-fuzzy">Desde 2015 (MediaWiki 1.26), os dispositivos devem utilizar o ResourceLoader ($1).</span> |
|||
{{ll|ResourceLoader}} is a core feature of MediaWiki that intelligently delivers JavaScript and CSS assets to users and readers. Because Gadgets are coded in JavaScript, as a Gadget coder you're bound to interact with ResourceLoader. |
<span lang="en" dir="ltr" class="mw-content-ltr">{{ll|ResourceLoader}} is a core feature of MediaWiki that intelligently delivers JavaScript and CSS assets to users and readers. Because Gadgets are coded in JavaScript, as a Gadget coder you're bound to interact with ResourceLoader.</span> |
||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
Your gadget should load useful ResourceLoader modules. |
Your gadget should load useful ResourceLoader modules. |
||
</div> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
* [[ResourceLoader/Modules|Modules]] — A list of JavaScript libraries, jQuery plugins and MediaWiki utilities that already exist within ResourceLoader for you to reuse. |
* [[ResourceLoader/Modules|Modules]] — A list of JavaScript libraries, jQuery plugins and MediaWiki utilities that already exist within ResourceLoader for you to reuse. |
||
</div> |
|||
** See the [http://docs.jquery.com/Main_Page jQuery documentation] for information about [[Special:MyLanguage/JQuery|using jQuery in MediaWiki]] |
|||
** Consulte a [https://api.jquery.com/ documentação jQuery] para informações sobre [[Special:MyLanguage/JQuery|a utilização do jQuery no MediaWiki]] |
|||
* [[Special:MyLanguage/ResourceLoader/Developing with ResourceLoader|Developing with ResourceLoader]] — A list of useful practices, like enabling the debug mode and help with debugging. |
|||
* [[Special:MyLanguage/ResourceLoader/Developing with ResourceLoader|Desenvolvendo com ResourceLoader]] — Uma lista de práticas úteis, como ativar o modo de depuração e ajudar a depurar. |
|||
** Also see the [[<tvar|RL>ResourceLoader/Migration_guide_(users)#Good_practices</>|ResourceLoader good practices]]. |
|||
** Também consulte as [[Special:MyLanguage/ResourceLoader/Migration guide (users)#Best practices|melhores práticas de ResourceLoader]]. |
|||
=== OOUI === |
=== OOUI === |
||
[[Special:MyLanguage/OOUI|OOUI]] |
[[Special:MyLanguage/OOUI|OOUI]] é uma biblioteca JavaScript com elementos de interface de usuário (por exemplo janelas pop-up) especificamente para uso no MediaWiki. |
||
A biblioteca [[Special:MyLanguage/OOUI/Using OOUI in MediaWiki#Gadgets|Utilizando OOUI em MediaWiki#Gadgets]] pode ser usada em dispositivos. |
|||
<span id="MediaWiki_Action_API"></span> |
|||
=== MediaWiki Action API === |
|||
=== API de Ação MediaWiki === |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">Within the context of a MediaWiki website the Action API can be accessed from JavaScript via the [[wmdoc:mediawiki-core/master/js/mw.Api.html|mw.Api]] JavaScript API.</span> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">([[wmdoc:mediawiki-core/master/js/mw.ForeignApi.html|mw.ForeignApi]] for allowed cross-site requests, e.g. between WMF wikis.)</span> |
|||
Consulte [[Special:MyLanguage/API|API]] para maiores informações. |
|||
{{note|1=<span lang="en" dir="ltr" class="mw-content-ltr">If your gadget makes API requests directly, add the "<code>?callback=?</code>" parameter to the API URL if you are trying to make an API request that would violate the [[w:same-origin policy|same-origin policy]] (e.g. making a request to the Commons API from Wikipedia). This triggers the use of [[w:JSONP|JSONP]] and enforces certain [[Special:MyLanguage/API:Data formats#JSON callback restrictions|restrictions]].</span>}} |
|||
See [[Special:MyLanguage/API]] for more information. |
|||
{{note|1=If your gadget uses the MediaWiki API, add the "<code>?callback=?</code>" parameter to the API URL if you are trying to make an API request that would violate the [[w:same-origin policy|same-origin policy]] (e.g. making a request to the Commons API from Wikipedia). This triggers the use of [[w:JSONP|JSONP]] and enforces certain [[API:Data formats#JSON callback restrictions|restrictions]].}} |
|||
=== VisualEditor === |
=== VisualEditor === |
||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
See [[VisualEditor/Gadgets|VisualEditor/Gadgets]] for a tutorial specifically for [[VisualEditor]] gadgets. |
See [[VisualEditor/Gadgets|VisualEditor/Gadgets]] for a tutorial specifically for [[VisualEditor]] gadgets. |
||
</div> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
=== Debugging user scripts and gadgets === |
=== Debugging user scripts and gadgets === |
||
</div> |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">Gadgets are usually compacted by the ResourceLoader, minimized and aggregated.</span> <span lang="en" dir="ltr" class="mw-content-ltr">Use the [[Special:MyLanguage/Help:Locating broken scripts|<code>debug=true</code> URI parameter (preceded by <code>?</code> or <code>&</code>, of course)]], to ask for the non-compacted version of the page and to load the "original source form" of your gadget.</span> <span lang="en" dir="ltr" class="mw-content-ltr">Also see [[Special:MyLanguage/ResourceLoader/Developing with ResourceLoader|Developing with ResourceLoader]] for more information.</span> |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">Learn how to use the Developer Tools of your browser (for example how to disable the cache in your browser).</span> <span lang="en" dir="ltr" class="mw-content-ltr">See the corresponding documentation: [https://developers.google.com/web/tools/chrome-devtools Chrome/Chromium], [[devmo:Tools/Web Console|Firefox]], [http://msdn.microsoft.com/en-us/library/ie/dn255006 Internet Explorer], [https://help.opera.com/latest/advanced/#developerTools Opera], [https://developer.apple.com/library/mac/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Introduction/Introduction.html Safari].</span> |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">If an existing gadget has problems, you can also use the page [[Special:Gadgets]] to find the source code location of a gadget.</span> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
* Gadgets are usually compacted by the ResourceLoader, minimized and aggregated. Use the [[Help:Locating broken scripts|<code>debug=true</code> URI parameter (preceded by <code>?</code> or <code>&</code>, of course)]], to ask for the non-compacted version of the page and to load the "original source form" of your gadget. Also see [[Special:MyLanguage/ResourceLoader/Developing with ResourceLoader|Developing with ResourceLoader]] for more information. |
|||
* Learn how to use the Developer Tools of your browser (for example how to disable the cache in your browser). See the corresponding documentation: [https://developers.google.com/web/tools/chrome-devtools Chrome/Chromium], [https://developer.mozilla.org/en-US/docs/Tools/Web_Console Firefox], [http://msdn.microsoft.com/en-us/library/ie/dn255006 Internet Explorer], [https://help.opera.com/en/latest/advanced/#developerTools Opera], [https://developer.apple.com/library/mac/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/Introduction/Introduction.html Safari]. |
|||
* If an existing gadget has problems, you can also use the page [[Special:Gadgets]] to find the source code location of a gadget. |
|||
=== Privacy and external content === |
=== Privacy and external content === |
||
</div> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
You should not load external resources that may harm users privacy. In Wikimedia wikis, the following domains are considered safe: |
You should not load external resources that may harm users privacy. In Wikimedia wikis, the following domains are considered safe: |
||
</div> |
|||
* *.wiktionary.org |
* *.wiktionary.org |
||
* *.wikimedia.org |
* *.wikimedia.org |
||
* *.wikibooks.org |
* *.wikibooks.org |
||
* *.wikisource.org |
|||
* *.wikisource.org |
* *.wikisource.org |
||
* *.wikiversity.org |
* *.wikiversity.org |
||
Line 87: | Line 158: | ||
* www.mediawiki.org |
* www.mediawiki.org |
||
{{tip|1=There |
{{tip|1=<span lang="en" dir="ltr" class="mw-content-ltr">There ''was'' a [[Special:MyLanguage/Continuous integration/Jenkins|Jenkins]] job ([https://integration.wikimedia.org/ci/job/audit-resources/ job] [[git:integration/audit-resources/+/master|code]]) that automatically checked gadgets for this principle, but this job has not been actively run since 2022.</span>}} |
||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
== A more complex user script example == |
|||
=== Running code on page load === |
|||
Check out '''[[MediaWiki:Tutorial-QuickRC.js]]''' which uses ''mw.loader, mw.util, mw.html, mw.user'' from ResourceLoader, the MediaWiki Action API, a jQuery UI dialog, jQuery AJAX, and jQuery event binding. |
|||
</div> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
Copy and paste the contents of [[MediaWiki:Tutorial-QuickRC.js]] into your [[Special:MyPage/common.js]]. |
|||
The common task of running code as soon as the page is loaded has several pitfalls which even experienced editors fall into. |
|||
</div> |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">First of all, when your code works with elements of the DOM, run it on page load.</span> <span lang="en" dir="ltr" class="mw-content-ltr">Otherwise, your code may run too early.</span> <span lang="en" dir="ltr" class="mw-content-ltr">The general way to do it is to use jQuery's <code>[https://api.jquery.com/jquery/#jQuery3 $()]</code> function, which does the same as <code>[https://learn.jquery.com/using-jquery-core/document-ready/ $(document).ready()]</code>.</span> |
|||
The result should be the same as above, but now you can modify the script, play with it, and replace it with something else entirely. |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">However, if your code works with the content part of the page (the <code>#mw-content-text</code> element), you should use the <code>[https://doc.wikimedia.org/mediawiki-core/master/js/Hooks.html#~event:'wikipage.content' 'wikipage.content']</code> hook instead.</span> <span lang="en" dir="ltr" class="mw-content-ltr">This way your code will successfully reprocess the page when it is updated asynchronously and the hook is fired again.</span> <span lang="en" dir="ltr" class="mw-content-ltr">There are plenty of tools which do so, ranging from edit preview to watchlist autoupdate.</span> |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">Be sure to only work with the descendants of the <code>$content</code> element that your handler function takes and not the whole page.</span> <span lang="en" dir="ltr" class="mw-content-ltr">Otherwise, you may end up running the same code for the same elements many times.</span> <span lang="en" dir="ltr" class="mw-content-ltr">Note that the <code>'wikipage.content'</code> hook may be fired ''really'' many times.</span> |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">Be cautious about what comes in the <code>$content</code> argument of the handler function.</span> <span lang="en" dir="ltr" class="mw-content-ltr">You shouldn't assume it's the <code>#mw-content-text</code> element.</span> <span lang="en" dir="ltr" class="mw-content-ltr">It can be a small portion of the page, e.g. when it is previewed.</span> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">Code that works with page content and avoids the aforementioned pitfalls may look like this:</span> |
|||
{{note|1=Clicking "Preview" (or using the keyboard shortcut, typically <code>Shift+Alt+P</code>) in the editor will also execute the latest version of the script. This is a good way to iterate without saving the page. Remember, nothing is saved until you press "Publish page".}} |
|||
<syntaxhighlight lang="javascript"> |
|||
== Load an existing user script == |
|||
mw.hook( 'wikipage.content' ).add( function ( $content ) { |
|||
const $target = $content.find( '.targetClass' ); |
|||
if ( $target.length ) { |
|||
// Do things with $target |
|||
} |
|||
// Only perform some operations when it is #mw-content-text in the argument |
|||
In the previous section, you copied the content of a user script. In this section, you will load the existing script [[MediaWiki:Tutorial-QuickRC.js]] instead. |
|||
if ( $content.is( '#mw-content-text' ) ) { |
|||
# Ensure you are [[Special:Userlogin|logged in]]. |
|||
const $note = $( '<div>' ) |
|||
# Visit [[Special:MyPage/common.js]]. This page holds your [[Manual:Interface/JavaScript#Personal_scripts|personal JavaScript]] that is loaded on every page view (except for Special:Preferences). |
|||
.addClass( 'myScript-note' ) |
|||
# Either create the page or edit the page if it already exists. |
|||
.text( 'MyScript has successfully processed the content!' ); |
|||
# Copy the following text and paste it into the page: <pre>mw.loader.load('//www.mediawiki.org/w/index.php?title=MediaWiki:Tutorial-QuickRC.js&action=raw&ctype=text/javascript');</pre> |
|||
$content.prepend( $note ); |
|||
# Click "Publish changes". You should now have a link in the "Tools" section called "Quick changelog". |
|||
} |
|||
# Click "Quick changelog". You get a pop-up window. It shows you a subset of the [[Special:RecentChanges|recent changes]] on this website. |
|||
} ); |
|||
</syntaxhighlight> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">If your code works with page content and adds event handlers to DOM elements, then, instead of hooking to <code>'wikipage.content'</code> 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 <code>document</code> but filter events by a selector (see [https://api.jquery.com/on/#on-events-selector-data-handler jQuery's documentation]).</span> |
|||
=== Use a script on another Wikimedia wiki === |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">That is, instead of writing <syntaxhighlight lang="javascript" inline>$content.find( '.targetClass' ).on( 'click', ... )</syntaxhighlight> you can write <syntaxhighlight lang="javascript" inline>$( document ).on( 'click', '.targetClass', ... )</syntaxhighlight>.</span> |
|||
If you want to use a script on another Wikimedia website (for example English Wikipedia instead of MediaWiki.org), you perform the same steps as above: you tell ResourceLoader to load your code. Visit your [[w:Special:MyPage/common.js|common.js]] on English Wikipedia, and add the following: |
|||
<pre>mw.loader.load("//www.mediawiki.org/w/index.php?title=MediaWiki:Tutorial-QuickRC.js&action=raw&ctype=text/javascript");</pre> |
|||
=== Recording metrics === |
|||
You can also load the user script which you just created above, by changing <code>MediaWiki:Tutorial-QuickRC.js</code> in the previous line to <code>User:''YourName''/''YourScript''.js</code> (replace <code>''YourName''</code> and <code>''YourScript''</code> accordingly). |
|||
Some gadgets are serious business. When your gadget gets serious, you might want to instrument it for analytics purposes, for example to measure the click rate of specific UI elements added to a page by the gadget. |
|||
This first requires that you do not store the code of your user script in [[Special:MyPage/common.js]] itself but instead in a separate sub page of [[Special:MyPage|your user page]]. |
|||
{{Main|Gadget kitchen: recording metrics}} |
|||
This also helps to [[mw:ResourceLoader/Migration guide (users)#Keep gadgets central|keep code in one single place, so you have to update code in only one place]]. |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
=== Miscellaneous === |
|||
</div> |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">Gadget code doesn't have to follow [[Special:MyLanguage/Manual:Coding conventions/JavaScript|the JavaScript coding conventions]] for MediaWiki, but if you expect others to touch your code, it may be used as reference.</span> |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">If you're developing in an [[w:Integrated development environment|IDE]] like [[w:VS Code|VS Code]], you may use type definitions for [https://www.npmjs.com/package/types-mediawiki MediaWiki], [https://www.npmjs.com/package/@types/oojs OOjs], [https://www.npmjs.com/package/@types/oojs-ui OOUI], and [https://www.npmjs.com/package/@types/jquery jQuery] for [[w:code completion|code completion]] and [[w:type checking|type checking]].</span> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
== Disadvantages and problems of gadgets == |
== Disadvantages and problems of gadgets == |
||
</div> |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">Gadgets are developed by community members.</span> <span lang="en" dir="ltr" class="mw-content-ltr">As of today, there is no formal code review required for gadgets on Wikimedia sites (see [[phab:T71445]]).</span> <span lang="en" dir="ltr" class="mw-content-ltr">Please follow the best practices listed on this page.</span> |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">On Wikimedia sites, the process how to "promote" a user script to a gadget in the [[Special:Preferences#mw-prefsection-gadgets|"Gadgets"]] tab of the user preferences is not always clear.</span> <span lang="en" dir="ltr" class="mw-content-ltr">You will have to find an [[meta:Special:MyLanguage/Interface administrators|interface administrator]] and might have to provide deployment instructions to them.</span> |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">Wikimedia lacks a systematic process for re-using, modifying and contributing to existing user scripts and gadgets.</span> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
* Gadgets are developed by community members. As of today, there is no formal code review required for gadgets on Wikimedia sites (see [[phab:T71445]]). Please follow the best practices listed on this page. |
|||
* On Wikimedia sites, the process how to "promote" a user script to a gadget in the [[Special:Preferences#mw-prefsection-gadgets|"Gadgets"]] tab of the user preferences is not always clear. You will have to find an [[meta:Interface administrators|interface administrator]] and might have to provide deployment instructions to them. |
|||
* Wikimedia lacks a systematic process for re-using, modifying and contributing to existing user scripts and gadgets. |
|||
== Ideas what to work on == |
== Ideas what to work on == |
||
</div> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
If you want to write features that directly help Wikimedia community members, see: |
|||
Some Wikimedia community members may share their ideas what they would like to see implemented by someone else. |
|||
</div> |
|||
* [[phabricator:tag/wikidata-gadgets/]] - <span lang="en" dir="ltr" class="mw-content-ltr">you can do small fixes on already existing gadgets, or work on proposals</span> |
|||
* [[Gadget Kitchen/Requests]] in general, however that page does not look be popular so you might waste time. |
|||
* [[Gadget Kitchen/Requests]] - <span lang="en" dir="ltr" class="mw-content-ltr">not a popular page, so you might waste time</span> |
|||
* [[w:Wikipedia:User scripts/Requests]] for English Wikipedia |
|||
* <span lang="en" dir="ltr" class="mw-content-ltr">[[w:Wikipedia:User scripts/Requests]]</span> - <span lang="en" dir="ltr" class="mw-content-ltr">for English Wikipedia</span> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
== Deploying or enabling a gadget == |
== Deploying or enabling a gadget == |
||
</div> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
If your user script should become a gadget (see the [[#What are user scripts and gadgets?|definitions]] above) on a wiki, the following steps are needed: |
If your user script should become a gadget (see the [[#What are user scripts and gadgets?|definitions]] above) on a wiki, the following steps are needed: |
||
</div> |
|||
* Steps for the user script author: |
* <span lang="en" dir="ltr" class="mw-content-ltr">Steps for the user script author:</span> |
||
** Recruit an experienced developer to review your gadget code. There is no formal process to do so. |
** <span lang="en" dir="ltr" class="mw-content-ltr">Recruit an experienced developer to review your gadget code.</span> <span lang="en" dir="ltr" class="mw-content-ltr">There is no formal process to do so.</span> |
||
** Check with community members if there aren't any concerns with enabling the gadget on a wiki. For the website MediaWiki.org itself, this would be [[Project: |
** <span lang="en" dir="ltr" class="mw-content-ltr">Check with community members if there aren't any concerns with enabling the gadget on a wiki.</span> <span lang="en" dir="ltr" class="mw-content-ltr">For the website MediaWiki.org itself, this would be [[Project:Village Pump]].</span> |
||
** Recruit a site administrator with interface rights. See the page [[Special:ListUsers/interface-admin]] on your wiki. |
** <span lang="en" dir="ltr" class="mw-content-ltr">Recruit a site administrator with interface rights. See the page [[Special:ListUsers/interface-admin]] on your wiki.</span> |
||
* Steps for the interface administrator: |
* <span lang="en" dir="ltr" class="mw-content-ltr">Steps for the interface administrator:</span> |
||
** Copy your JS & CSS files in the <code>MediaWiki:</code> [[Help:Namespaces|namespace]] on your wiki, and make sure the page names have the prefix <code>Gadget-</code>.<br/>''Example:'' <code>MediaWiki:Gadget-userfeedback.js</code> |
** <span lang="en" dir="ltr" class="mw-content-ltr">Copy your JS & CSS files in the <code>MediaWiki:</code> [[Special:MyLanguage/Help:Namespaces|namespace]] on your wiki, and make sure the page names have the prefix <code>Gadget-</code>.</span><br/><span lang="en" dir="ltr" class="mw-content-ltr">''Example:''</span> <code>MediaWiki:Gadget-userfeedback.js</code> |
||
** Define the gadget on the [[MediaWiki:Gadgets-definition]] page of your wiki. That includes the modules used, dependencies, JS, and CSS file names, etc. This will allow users to enable the gadget on the [[Special:Preferences]] page of your wiki.<br/>''Example:'' <code>userfeedback[ResourceLoader|default|dependencies=ext.eventLogging]|userfeedback.js|userfeedback.css</code> |
** <span lang="en" dir="ltr" class="mw-content-ltr">Define the gadget on the [[MediaWiki:Gadgets-definition]] page of your wiki.</span> <span lang="en" dir="ltr" class="mw-content-ltr">That includes the modules used, dependencies, JS, and CSS file names, etc.</span> <span lang="en" dir="ltr" class="mw-content-ltr">This will allow users to enable the gadget on the [[Special:Preferences]] page of your wiki.</span><br/><span lang="en" dir="ltr" class="mw-content-ltr">''Example:''</span> <code>userfeedback[ResourceLoader|default|dependencies=ext.eventLogging]|userfeedback.js|userfeedback.css</code> |
||
** Create a page for the gadget in the <code>MediaWiki:</code> namespace with prefix <code>Gadget-</code>. This will generate a label for the gadget on the [[Special:Preferences]] page of your wiki.<br/>''Example:'' <code>MediaWiki:Gadget-userfeedback</code> |
** <span lang="en" dir="ltr" class="mw-content-ltr">Create a page for the gadget in the <code>MediaWiki:</code> namespace with prefix <code>Gadget-</code>.</span> <span lang="en" dir="ltr" class="mw-content-ltr">This will generate a label for the gadget on the [[Special:Preferences]] page of your wiki.</span><br/><span lang="en" dir="ltr" class="mw-content-ltr">''Example:''</span> <code>MediaWiki:Gadget-userfeedback</code> |
||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
== Contributing to user scripts == |
|||
</div> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">If a user script is made by another user you may be able to contribute to it.</span> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">You can do this by making a copy of the user script as a subpage of your own user page.</span> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">Then replace the original user script you had enabled with the one that is a user page in your common.js.</span> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">Proceed to make edits as you please to your copy of the script.</span> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">If you want the script to contain the changes you made to your copy of the script, you should ping the author of the script on the discussion page of the original user script with the page that contains your changes and ask them to add the changes.</span> |
|||
<span lang="en" dir="ltr" class="mw-content-ltr">If the user is no longer active, then you should notify the community that your version of the script exists by linking the script on your wiki's list of scripts.</span> |
|||
<div lang="en" dir="ltr" class="mw-content-ltr"> |
|||
== Related pages == |
== Related pages == |
||
</div> |
|||
* [[w |
* <span lang="en" dir="ltr" class="mw-content-ltr">[[w:Wikipedia:User scripts|Wikipedia:User scripts]] on the English Wikipedia and its alternatives in other languages are the primary hubs for user script and gadget development in Wikipedia.</span> |
||
** The [[w:Wikipedia:WikiProject User scripts/Guide|user scripts guide]] on the English Wikipedia has ''tons'' of useful information to get you started. |
** <span lang="en" dir="ltr" class="mw-content-ltr">The [[w:Wikipedia:WikiProject User scripts/Guide|user scripts guide]] on the English Wikipedia has ''tons'' of useful information to get you started.</span> |
||
* [[w:en:Wikipedia:Gadget|Wikipedia:Gadget]] page on English Wikipedia |
* <span lang="en" dir="ltr" class="mw-content-ltr">[[w:en:Wikipedia:Gadget|Wikipedia:Gadget]] page on English Wikipedia</span> |
||
* [[c:File:Userscript and Gadgets workshop toolkit.pdf|Slides for a workshop to teach the basics of user scripts and gadgets]] (part of [[meta:Small wiki toolkits]]) |
* <span lang="en" dir="ltr" class="mw-content-ltr">[[c:File:Userscript and Gadgets workshop toolkit.pdf|Slides for a workshop to teach the basics of user scripts and gadgets]] (part of [[meta:Small wiki toolkits]])</span> |
||
* [[m:Gadgets|List of gadgets by popularity across all Wikimedia projects]] |
* <span lang="en" dir="ltr" class="mw-content-ltr">[[m:Gadgets|List of gadgets by popularity across all Wikimedia projects]]</span> |
||
* For a specific website, see [[Special:GadgetUsage]] for the number of users that each gadget has |
* <span lang="en" dir="ltr" class="mw-content-ltr">For a specific website, see [[Special:GadgetUsage]] for the number of users that each gadget has</span> |
||
* [[Special:MyLanguage/Compatibility#Browsers|Compatibility]] - MediaWiki's JavaScript support per browser and browser version |
* [[Special:MyLanguage/Compatibility#Browsers|<span lang="en" dir="ltr" class="mw-content-ltr">Compatibility</span>]] - <span lang="en" dir="ltr" class="mw-content-ltr">MediaWiki's JavaScript support per browser and browser version</span> |
||
* [[c:File:Customizing Wikipedia with Javascript - User Scripts and Gadgets - San Francisco Wikipedia Hackathon 2012.ogv|A video tutorial from the year 2012 regarding gadgets and user scripts.]] This is a bit outdated and the quality could be better, but shows how to use developer tools etc. |
* [[c:File:Customizing Wikipedia with Javascript - User Scripts and Gadgets - San Francisco Wikipedia Hackathon 2012.ogv|A video tutorial from the year 2012 regarding gadgets and user scripts.]] <span lang="en" dir="ltr" class="mw-content-ltr">This is a bit outdated and the quality could be better, but shows how to use developer tools etc.</span> |
||
* See |
* <span lang="en" dir="ltr" class="mw-content-ltr">See {{ll|Extension:EventLogging}} for a mechanism to gather data created from users interacting with a gadget.</span> |
||
* <span lang="en" dir="ltr" class="mw-content-ltr">[[:Category:Snippets with JavaScript]] – useful JavaScript snippets</span> |
|||
{{note|1=In the future, changes to ResourceLoader ([[phab:T31272|"Gadgets 2.0"]]) will make managing gadgets simpler.}} |
|||
[[Category:MediaWiki development{{#translation:}}]] |
[[Category:MediaWiki development{{#translation:}}]] |
Latest revision as of 08:09, 7 September 2024
Receba as boas-vindas à cozinha de gadgets. Este é um tutorial de como pode escrever e utilizar gadgets e scripts pessoais em JavaScript.
O que são scripts pessoais e gadgets?
O MediaWiki permite que todos escrevam código JavaScript público para alterar imediatamente o comportamento do software. Este código pode ser compartilhado com outros usuários. Este código localiza-se em páginas wikis.
- A user script can be edited by the original author (if it is stored in the
User:
namespace) and by anyone with the "edituserjs" user right (usually just interface administrators).
The code is usually hosted on a subpage of your user page. Examples include: XTools/ArticleInfo.js and m:User:Hoo man/useful links.js. User scripts are similar to the personal JavaScript pages such as Special:MyPage/common.js, but they allow single code chunks to be shared with other users.
- Um gadget é um script pessoal que foi "promovido" por um administrador de interface, adicionando-o à página MediaWiki:Gadgets-definition. Usuários registrados podem ativar gadgets na aba "Gadgets" de suas preferências de usuário. Os gadgets são criados e gerenciados por administradores de interface.
- Para completude: Também há o siteJS localizado na página MediaWiki:Common.js. O JavaScript naquela página afeta todos os usuários e é executado automaticamente tanto para usuários registrados quanto para não registrados. Interface administrators can edit them. Read Manual:Interface/JavaScript for detailed information.
Se estiver executando sua própria cópia do MediaWiki, $wgAllowUserJs
precisa estar ativado para que scripts de usuário funcionem, e a extensão Gadgets precisa ser instalada para possibilitar a promoção de scripts individuais para o status de gadget.
Para uma experiência de desenvolvimento melhor, certifique-se de que a extensão CodeEditor esteja instalada em sua wiki.
Write your first user script
In this section, you create an example user script which calculates the estimated reading time of a wiki page.
- Ensure you are logged in.
- Visit Special:MyPage/common.js. This page holds your personal JavaScript that is loaded on every page view (except for Special:Preferences).
- Either create the page or edit the page if it already exists.
- Copy the following six lines and paste these lines into the page:
var numWords = $("#mw-content-text > div").text().split(" ").length; var headerWords = $("h1").text().split(" ").length; var totalWords = numWords + headerWords; var timeInMinutes = totalWords / 200; var header = $("h1").text(); $("h1").text(header + " (it will take you " + timeInMinutes + " minutes to read this page)");
- Click "Publicar alterações".
- Go to any page. Look at the title.
This example user script is taken from ChickTech High School Kickoff 2017/Tasks . There are more examples for simple user scripts on that page.
A more complex user script example
Check out MediaWiki:Tutorial-QuickRC.js which uses mw.loader, mw.util, mw.html, mw.user from ResourceLoader, the MediaWiki Action API, a jQuery UI dialog, jQuery AJAX, and jQuery event binding.
Copy and paste the contents of MediaWiki:Tutorial-QuickRC.js into your Special:MyPage/common.js.
The result should be the same as above, but now you can modify the script, play with it, and replace it with something else entirely.
Load an existing user script
In the previous section, you copied the content of a user script. In this section, you will load the existing script MediaWiki:Tutorial-QuickRC.js instead.
- Ensure you are logged in.
- Visit Special:MyPage/common.js. This page holds your personal JavaScript that is loaded on every page view (except for Special:Preferences).
- Either create the page or edit the page if it already exists.
- Copy the following text and paste it into the page:
mw.loader.load('//www.mediawiki.org/w/index.php?title=MediaWiki:Tutorial-QuickRC.js&action=raw&ctype=text/javascript');
- Click "Publish changes". You should now have a link in the "Tools" section called "Quick changelog".
- Click "Quick changelog". You get a pop-up window. It shows you a subset of the recent changes on this website.
Use a script on another Wikimedia wiki
If you want to use a script on another Wikimedia website (for example English Wikipedia instead of MediaWiki.org), you perform the same steps as above: you tell ResourceLoader to load your code. Visit your common.js on English Wikipedia, and add the following:
mw.loader.load("//www.mediawiki.org/w/index.php?title=MediaWiki:Tutorial-QuickRC.js&action=raw&ctype=text/javascript");
You can also load the user script which you just created above, by changing MediaWiki:Tutorial-QuickRC.js
in the previous line to User:YourName/YourScript.js
(replace YourName
and YourScript
accordingly).
This first requires that you do not store the code of your user script in Special:MyPage/common.js itself but instead in a separate sub page of your user page.
This also helps to keep code in one single place, so you have to update code in only one place.
Desenvolvimento de scripts pessoais e gadgets
This section lists resources which are either needed or helpful for non-simple user scripts.
ResourceLoader
Desde 2015 (MediaWiki 1.26), os dispositivos devem utilizar o ResourceLoader ($1). Resource Loader is a core feature of MediaWiki that intelligently delivers JavaScript and CSS assets to users and readers. Because Gadgets are coded in JavaScript, as a Gadget coder you're bound to interact with ResourceLoader.
Your gadget should load useful ResourceLoader modules.
- Modules — A list of JavaScript libraries, jQuery plugins and MediaWiki utilities that already exist within ResourceLoader for you to reuse.
- Consulte a documentação jQuery para informações sobre a utilização do jQuery no MediaWiki
- Desenvolvendo com ResourceLoader — Uma lista de práticas úteis, como ativar o modo de depuração e ajudar a depurar.
- Também consulte as melhores práticas de ResourceLoader.
OOUI
OOUI é uma biblioteca JavaScript com elementos de interface de usuário (por exemplo janelas pop-up) especificamente para uso no MediaWiki. A biblioteca Utilizando OOUI em MediaWiki#Gadgets pode ser usada em dispositivos.
API de Ação MediaWiki
Within the context of a MediaWiki website the Action API can be accessed from JavaScript via the mw.Api JavaScript API. (mw.ForeignApi for allowed cross-site requests, e.g. between WMF wikis.) Consulte API para maiores informações.
?callback=?
" parameter to the API URL if you are trying to make an API request that would violate the same-origin policy (e.g. making a request to the Commons API from Wikipedia). This triggers the use of JSONP and enforces certain restrictions.VisualEditor
See VisualEditor/Gadgets for a tutorial specifically for VisualEditor gadgets.
Debugging user scripts and gadgets
- Gadgets are usually compacted by the ResourceLoader, minimized and aggregated. Use the
debug=true
URI parameter (preceded by?
or&
, of course), to ask for the non-compacted version of the page and to load the "original source form" of your gadget. Also see Developing with ResourceLoader for more information. - Learn how to use the Developer Tools of your browser (for example how to disable the cache in your browser). See the corresponding documentation: Chrome/Chromium, Firefox, Internet Explorer, Opera, Safari.
- If an existing gadget has problems, you can also use the page Special:Gadgets to find the source code location of a gadget.
Privacy and external content
You should not load external resources that may harm users privacy. In Wikimedia wikis, the following domains are considered safe:
- *.wiktionary.org
- *.wikimedia.org
- *.wikibooks.org
- *.wikisource.org
- *.wikiversity.org
- *.wikinews.org
- *.wikiquote.org
- *.wikidata.org
- *.wikivoyage.org
- www.mediawiki.org
Running code on page load
The common task of running code as soon as the page is loaded has several pitfalls which even experienced editors fall into.
- First of all, when your code works with elements of the DOM, run it on page load. Otherwise, your code may run too early. The general way to do it is to use jQuery's
$()
function, which does the same as$(document).ready()
. - 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 which 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 shouldn't assume it's 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:
mw.hook( 'wikipage.content' ).add( function ( $content ) {
const $target = $content.find( '.targetClass' );
if ( $target.length ) {
// Do things with $target
}
// Only perform some operations when it is #mw-content-text in the argument
if ( $content.is( '#mw-content-text' ) ) {
const $note = $( '<div>' )
.addClass( 'myScript-note' )
.text( 'MyScript has successfully processed the content!' );
$content.prepend( $note );
}
} );
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 $content.find( '.targetClass' ).on( 'click', ... )
you can write $( document ).on( 'click', '.targetClass', ... )
.
Recording metrics
Some gadgets are serious business. When your gadget gets serious, you might want to instrument it for analytics purposes, for example to measure the click rate of specific UI elements added to a page by the gadget.
Miscellaneous
- Gadget code doesn't have to follow the JavaScript coding conventions for MediaWiki, but if you expect others to touch your code, it may be used as reference.
- If you're developing in an IDE like VS Code, you may use type definitions for MediaWiki, OOjs, OOUI, and jQuery for code completion and type checking.
Disadvantages and problems of gadgets
- Gadgets are developed by community members. As of today, there is no formal code review required for gadgets on Wikimedia sites (see phab:T71445). Please follow the best practices listed on this page.
- On Wikimedia sites, the process how to "promote" a user script to a gadget in the "Gadgets" tab of the user preferences is not always clear. You will have to find an interface administrator and might have to provide deployment instructions to them.
- Wikimedia lacks a systematic process for re-using, modifying and contributing to existing user scripts and gadgets.
Ideas what to work on
Some Wikimedia community members may share their ideas what they would like to see implemented by someone else.
- phabricator:tag/wikidata-gadgets/ - you can do small fixes on already existing gadgets, or work on proposals
- Gadget Kitchen/Requests - not a popular page, so you might waste time
- w:Wikipedia:User scripts/Requests - for English Wikipedia
Deploying or enabling a gadget
If your user script should become a gadget (see the definitions above) on a wiki, the following steps are needed:
- Steps for the user script author:
- Recruit an experienced developer to review your gadget code. There is no formal process to do so.
- Check with community members if there aren't any concerns with enabling the gadget on a wiki. For the website MediaWiki.org itself, this would be Project:Village Pump.
- Recruit a site administrator with interface rights. See the page Special:ListUsers/interface-admin on your wiki.
- Steps for the interface administrator:
- Copy your JS & CSS files in the
MediaWiki:
namespace on your wiki, and make sure the page names have the prefixGadget-
.
Example:MediaWiki:Gadget-userfeedback.js
- Define the gadget on the MediaWiki:Gadgets-definition page of your wiki. That includes the modules used, dependencies, JS, and CSS file names, etc. This will allow users to enable the gadget on the Special:Preferences page of your wiki.
Example:userfeedback[ResourceLoader|default|dependencies=ext.eventLogging]|userfeedback.js|userfeedback.css
- Create a page for the gadget in the
MediaWiki:
namespace with prefixGadget-
. This will generate a label for the gadget on the Special:Preferences page of your wiki.
Example:MediaWiki:Gadget-userfeedback
- Copy your JS & CSS files in the
Contributing to user scripts
If a user script is made by another user you may be able to contribute to it. You can do this by making a copy of the user script as a subpage of your own user page. Then replace the original user script you had enabled with the one that is a user page in your common.js. Proceed to make edits as you please to your copy of the script. If you want the script to contain the changes you made to your copy of the script, you should ping the author of the script on the discussion page of the original user script with the page that contains your changes and ask them to add the changes. If the user is no longer active, then you should notify the community that your version of the script exists by linking the script on your wiki's list of scripts.
Related pages
- Wikipedia:User scripts on the English Wikipedia and its alternatives in other languages are the primary hubs for user script and gadget development in Wikipedia.
- The user scripts guide on the English Wikipedia has tons of useful information to get you started.
- Wikipedia:Gadget page on English Wikipedia
- Slides for a workshop to teach the basics of user scripts and gadgets (part of meta:Small wiki toolkits)
- List of gadgets by popularity across all Wikimedia projects
- For a specific website, see Special:GadgetUsage for the number of users that each gadget has
- Compatibility - MediaWiki's JavaScript support per browser and browser version
- A video tutorial from the year 2012 regarding gadgets and user scripts. This is a bit outdated and the quality could be better, but shows how to use developer tools etc.
- See Extension:EventLogging for a mechanism to gather data created from users interacting with a gadget.
- Category:Snippets with JavaScript – useful JavaScript snippets