Adding javascript to wiki pages

From MediaWiki.org
(Redirected from Adding HTML to wiki pages)
Jump to navigation Jump to search

By using JavaScript files in the MediaWiki namespace and allowed HTML in the Template namespace, it is possible to add any HTML and JavaScript to wiki pages securely.

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.

Adding the HTML and JavaScript[edit]

Creating the script[edit]

JavaScript programs can be written on the MediaWiki:Common.js page on your wiki. You will need to write JavaScript even if you only are using HTML because JavaScript is what will add the HTML elements to the page.

In case of HTML content, the script will contain the HTML you want to add and identify where to put it.

Use the following example to write your script.

$(function () {

  var myElement = document.getElementById('mw-mywiki-example');
  myElement.innerHTML = 'any HTML';

}());

jQuery is also shipped with MediaWiki core. You can write your script like this:

$(function () {
  $('#mw-mywiki-example').html('any HTML');
}());

When copying the script, change mw-mywiki-example to the identifier you will use inside your wiki page. For example, mw-unicornwiki-ads.

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.

Separate script[edit]

If your script gets too long or you want to keep snippets from a third-party library separate, you can create a new file in the MediaWiki namespace (ending in .js), e.g. MediaWiki:Example.js. And then instruct MediaWiki to import that script. To do this, add an import script instruction to MediaWiki:Common.js:

mw.loader.load( '/w/index.php?title=MediaWiki:Example.js&action=raw&ctype=text/javascript' );

Enable on a wiki page[edit]

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

Add the following code to the template. Make sure the ID matches the identifier you specified in your script earlier.

<div id="mw-mywiki-example"></div>

You can use any tags or attributes to style the template and the content being added. Just make sure that you keep the identifier the same.

Enable it on a page by including the template on any wiki page(s) you want the script to apply:

{{Advertisement}}