Wikipedia:User scripts/Guide: Difference between revisions

Content deleted Content added
Editing and loading the user script: Adding more explanation to section "Publishing a CSS file".
Alex Smotrov (talk | contribs)
fixing "built-in scripts"; simplifying "structure" a lot; adding ==Local HTML file==; re-adding localhost limitation for Opera 9.50+; fixing and moving up "Browser-specific" and next
Line 4:
This is a small guide on writing user scripts for [[Wikimedia Foundation|Wikimedia]] sites. Of course, some basic [[JavaScript]] knowledge is required. (See also [[JavaScript syntax]].)
 
== ScriptsBuilt-in scripts ==
All Wikipedia pages include some built-in [[MediaWiki]] JavaScript code, with variables and functions that can be utilized 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]].
The following script files are executed for every Wikipedia visitor:
 
Of most interest are:
* some <tt>(wg)</tt> variables in the beginning of the page
* more than 30 project-, page- and user-specific variables at the top of the HTML page
* [{{SERVER}}/skins-1.5/common/wikibits.js '''wikibits.js'''] — shared by all [[Wikimedia]] projects
* [{{SERVER}}/skins-1.5/common/wikibits.js wikibits.js]
* '''[[MediaWiki:Common.js]]''' (as [{{SERVER}}{{SCRIPTPATH}}/index.php?title=-&amp;action=raw&amp;smaxage=0&amp;gen=js generated]), supported by local [[Wikipedia:Administrators|Administrators]]
* [[MediaWiki:Common.js]] (as [{{SERVER}}{{SCRIPTPATH}}/index.php?title=-&amp;action=raw&amp;smaxage=0&amp;gen=js generated]), supported by local [[Wikipedia:Administrators|Administrators]]
* [[Special:MyPage/monobook.js|monobook.js]] — your own script file, if you created one
* [[Special:MyPage/monobook.js|monobook.js]] (exact name depends on the [[Wikipedia:Skin|skin]] in your preferences) which is your own script file
* [{{SERVER}}/skins-1.5/common/ajax.js '''ajax.js'''] — shared by all [[Wikimedia]] projects
It is recommended that you save the «system» script files locally and view them with your text editor (with syntax highlighting). There are some useful functions there that you can use in your scripts, some of them are mentioned below.
 
== Userscript structure ==
 
Personal <tt>/monobook.js</tt> and [[Wikipedia:Gadget|gadgets]] are included early in the generated [[HTML]] page. This means that in most cases we need to defer the script actions until the page is loaded. The most common way is to use a special <code>function addOnloadHook()</code> from wikibits.js.
 
<source lang="javascript">
== Structure ==
//Define our main function
function myScript(){
//... code ...
}
 
//Schedule it to run after HTML page is rendered
When your <tt>/monobook.js</tt> is executed most [[HTML]] page elements do not exist yet. So most user scripts look like this:
addOnloadHook(myScript)
</source>
 
Since the function is called only once, many users prefer to shorten this code with "anonymous function call":
<source lang="javascript">
addOnloadHook(function(){
//Part 1
//... code ...
addOnloadHook( function() { //Means execute "function()" later.
})
</source>
 
Many scripts use this function simply to add some script interface, such as a link in a leftside portlet. Then the main part of the code is executed after user clicks on that link.
//Part 2 — executed when the page has loaded
 
//Quite often it simply adds a JavaScript link
<a onclick="func_action()" href="#">
 
} );
 
//And then there is …
 
//Part 3 — executed when the user clicks on this link
function func_action (){
}
</source>
 
== BasicDHTML methods ==
 
=== Finding elements ===
Line 124 ⟶ 122:
|}
</div>
 
 
There is a special function in [{{SERVER}}/skins-1.5/common/wikibits.js wikibits.js] that simplifies the process of adding your own links into portlets:<br/>
Line 141 ⟶ 138:
* <tt>nextnode</tt> — if you want to insert new link before another element, in our example this could be <code>document.getElementById('t-specialpages')</code>, i.e. «Special pages» link
-->
 
 
=== Adding elements ===
Line 161 ⟶ 157:
 
2) using DOM methods: <tt>'''CreateElement'''</tt>, then atach as child using <tt>'''AppendChild'''</tt> or <tt>'''InsertBefore'''</tt>. For examples of usage see the code of <tt>addPortletLink()</tt>
 
 
=== Removing elements ===
Line 176 ⟶ 171:
 
This is easier with [[Special:Mypage/monobook.css|your monobook.css]] though: <code style="white-space:nowrap">#editpage-copywarn {display:none}</code>
 
 
== Edit page ==
Line 189 ⟶ 183:
There is a function in wikibits.js that can add text to cursor position: <br/>
'''insertTags''' (tagOpen, tagClose, sampleText)
 
 
=== Toolbar ===
Line 205 ⟶ 198:
 
Also see [[:en:User:MarkS/Extra_edit_buttons]].
 
 
=== Edittools ===
There is another edit panel under textarea. ItUsually it's generated from [[MediaWiki:Edittools]] by [[mw:Extension:CharInsert|Extension:CharInsert]], itand consists of a lot of javascript links to the <tt>insertTags()</tt>. In English Wikipedia this approach was replaced by [[MediaWiki:Edittools.js]].
 
<source lang="javascript">
Line 219 ⟶ 211:
 
There is no crucial difference between toolbar and edittools, you can insert your own custom links into both.
<!--
== Misc ==
Unnamed function:
<source lang="javascript">
addOnloadHook(function(){
// … …
});
</source>
 
:en:Wikipedia:Keyboard_shortcuts
-->
 
== Editing and loading the user script ==
Line 240 ⟶ 221:
If required elements are missing on the preview page (for example, your script does something on history pages), you will have to save the script in order to test it.
 
However it's not convenient and creates unnecessary load on the WikiMedia servers. (ItAlso, usuallyit involvesseems waitinglike forthese somedays minuteWikimedia afterservers youare savedconfigured yournot to give out the saved /monobook.js version right away, so you have to wait some minute after saving and then [[Wikipedia:Bypass your cache|bypassing your browser cache]].)
 
=== Local HTML file ===
* Save Wikipedia page to your local hard drive, including all corresponding .css and .js files. Specific details depend on your browser. <!--how-to might be nice-->
* Open saved page in your editor, insert your script code either between <code>&lt;script>&lt;/script></code> tags or as a separate local file with <code>&lt;script src="file://C://you_local_path/name.js"&lt;/script></code>.
* Open saved page in your browser and preview the result.
 
This is a very traffic-wise way to quickly develop a user script. However, it has the following disadvantages:
* browser will not let you test Ajax queries from a local file
* you have to save different pages depending on what exactly page (history, etc.) is needed for testing
* you have to periodically re-save all .js files to synchronize with MediaWiki changes
* if you want to "casually" test the script while you're browsing Wikipedia, you still have to use other testing methods
 
=== Load from a localhost web server ===
Line 255 ⟶ 247:
 
For example you could use [http://www.ritlabs.com/en/products/tinyweb/ TinyWeb] which is less than 100kbyte on disk and doesn't require installation. Save and unzip <tt>tinyweb.zip</tt> for example into <tt>c:\Program Files\Tinyweb</tt>, then create a shortcut to <tt>tiny.exe</tt>, in shortcut properties add an argument — path to your folder with <tt>wikipediatest.js</tt> and any file <tt>index.html</tt> (required). Start TinyWeb with this shortcut; unload it with Task Manager.
 
Note that this method doesn't work in latest [[Opera (web browser)|Opera]] browser due to added security restriction, see [http://www.opera.com/docs/changelogs/windows/950/ Opera 9.50 for Windows changelog]: "Local servers can use remote resources, but not vice versa".
 
=== Browser-specific ===
Some browsers allow you to automatically execute your javascript code on specific web pages. This way you don't even have to be logged in.
 
The most famous solution is [[Greasemonkey]] for Firefox browsers. Some alternatives for other browsers are listed at [[Greasemonkey#Greasemonkey compatibility and equivalents for other browsers]].
 
However, making userscript work with one of these extensions might require some modifications to the script code.
 
Some notes for [[Opera (web browser)|Opera]]:
* placing your script in a corresponding folder as <code><name>.user.js</code> file should work for many userscripts
* older versions of Opera (probably below 9.50) did not support [[UTF-8]] local scripts, meaning you could only use latin characters
 
=== Pieces of code ===
You can run pieces of code on already loaded pages, for example directly in the browser address field: <code>javascript: var s = document.title; alert(s); void 0</code>
 
Or you can use [[bookmarklet]] «JavaScript Shell». It opens new browser window where you can paste or type your code and run it in the context of the current page.
* [http://www.squarefree.com/shell/ JavaScript Shell for FireFox and Opera]
* [http://blog.monstuff.com/archives/000287.html JavaScript Shell for IE]
 
However a full-blown Javascript debugger is much more convenient.
 
=== Publishing your user script ===
Line 264 ⟶ 278:
</source>
 
=== CSS files ===
 
Some user scripts also use some CSS code, or even are built with CSS only. Then you need to code and test CSS code. That can be done in your <tt>/monobook.css</tt>, but that is slow and messy.
Line 294 ⟶ 308:
@import "/w/index.php?title=User:Yourname/yourscript.css&action=raw&ctype=text/css";
</source>
 
=== Other methods ===
 
You can also debug your scripts:
* in [[FireFox]] with [[Greasemonkey]]
* in [[Opera]] with [http://www.opera.com/support/tutorials/userjs/using/ User JavaScript]
* in [[Internet Explorer]] 6 (and maybe in some other browsers) with [[bookmarklet]]
 
<source lang="javascript">
javascript: var s = document.createElement('script');
s.src = 'file://C:/myscript.js';
document.getElementsByTagName('head')[0].appendChild(s);void 0
</source>
 
However all these methods execute your user script at slightly different time than <tt>monobook.js</tt>, so you might have to do some temporary code modifications during debugging.
<!--
=== Pieces of code ===
You can run pieces of code on already loaded pages, for example directly in the browser address field: <code>javascript: var s = document.title; alert(s); </code>
 
Or you can use [[bookmarklet]] «JavaScript Shell». It opens new browser window where you can paste or type your code and run it in the context of the current page.
* [http://www.squarefree.com/shell/ JavaScript Shell for FireFox and Opera]
* [http://blog.monstuff.com/archives/000287.html JavaScript Shell for IE]
 
However a full-blown Javascript debugger is much more convenient.
-->
 
== Software ==
Line 329 ⟶ 318:
* show the list of all functions and quickly jump to any function
* [[Code folding]]
 
 
 
For debugging in [[Firefox]] you can use Tools → Javascript Console which shows all Javascript and CSS errors. [http://getfirebug.com/ FireBug] is strongly recommended for convenient debugging.