[go: nahoru, domu]

Jump to content

How to enhance wiki content with JavaScript

From mediawiki.org
Revision as of 17:56, 9 May 2014 by 149.155.222.31 (talk) (I just tried exactly what this page described and it didn't work. Then I realized it might have meant the Commons.js instead of the Commons.css page (makes more sense) so I tried that and it does work, so I made the fix here.)

As a security precaution to prevent attacks against the wiki, many HTML tags and all JavaScript is disabled in regular wikitext. This means that you cannot copy Google AdSense banners, Disqus comment boxes, Facebook like buttons, or any other embeddable objects into the source code of a page. You should also never allow any HTML or JavaScript to be useable in page source code because of the severe security vulnerabilities, which include allowing an attacker to gather literally every password used by all wiki users. By using JavaScript files in the system namespace and allowed HTML in pages, it is possible to add any HTML and JavaScript to wiki pages securely.

Adding the HTML and JavaScript

Creating the script

JavaScript files can be created in the system namespace (MediaWiki:) by ending the page name with .js. An example script would be MediaWiki:YourScript.js. You will need to create a JavaScript file even if you only are using HTML because JavaScript is what adds the object to the page to bypass the filter on the wikitext.

This script will contain the HTML or JavaScript that you plan to add and identify where to place it.

Use the following JavaScript to create the script.

var newPageElement = document.getElementById('some-element');

newPageElement.innerHTML = 'any HTML';

When copying the script, change newPageElement to whatever you are adding. For example, you could use facebookLike.

Also change some-element to the HTML ID name of what you want the new object to be. For example, facebookLikeID.

To add the HTML or JavaScript, change any HTML to whatever HTML code that you want. Be careful about double and single quotes and use JavaScript escape characters where necessary.

Enabling the script

Now you will need to instruct MediaWiki to execute your script. To do this, add an import script instruction to MediaWiki:Common.js. For the example script, this can be done with:

importScript('MediaWiki:YourScript.js');

Adding the object to wiki pages

To begin adding the new object to wiki pages, create a template. For example, it could be called Template:FacebookLike.

Add the following code to the template. Make sure the ID is the same as the ID that you specified in your script.

You can use any tags or attributes to style the template and the object being added; just make sure that you keep the ID the same.

Add the template anywhere on wiki pages where you want the object to display.