plugin_development.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. .. raw:: html
  2. <div id="banner"><a href="https://github.com/jcbrand/converse.js/blob/master/docs/source/theming.rst">Edit me on GitHub</a></div>
  3. .. _`writing-a-plugin`:
  4. Writing a plugin
  5. ================
  6. Introduction
  7. ------------
  8. Converse.js is exposes a plugin architecture which allows developers to modify
  9. and extend its functionality.
  10. Specifically, plugins enable developers to extend and override existing objects,
  11. functions and `Backbone <http://backbonejs.org/>`_ models and views that make up
  12. Converse.js, and also give them the ability to write new models and views.
  13. Various core features of Converse.js, such as
  14. `Message Archive Management <https://xmpp.org/extensions/xep-0313.html>`_ and
  15. `Group chats <https://xmpp.org/extensions/xep-0045.html>`_ are implemented
  16. as plugins, thereby showing their power and flexibility.
  17. Converse.js uses `pluggable.js <https://github.com/jcbrand/pluggable.js/>`_ as
  18. its plugin architecture.
  19. To more deeply understand how this plugin architecture works, please read the
  20. `pluggable.js documentation <https://jcbrand.github.io/pluggable.js/>`_
  21. and to understand its inner workins, please refer to the `annotated source code
  22. <https://jcbrand.github.io/pluggable.js/docs/pluggable.html>`_.
  23. Trying out a plugin in JSFiddle
  24. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  25. Because Converse.js consists only of JavaScript, HTML and CSS (with no backend
  26. code required like PHP, Python or Ruby) it runs fine in JSFiddle.
  27. Here's an Fiddle with a Converse.js plugin that calls `alert` once it gets
  28. initialized and also when a chat message gets rendered:
  29. https://jsfiddle.net/4drfaok0/15/
  30. Generating a plugin with Yeoman
  31. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  32. The rest of this document explains how to write a plugin for Converse.js, and
  33. ends with a documented example of a plugin.
  34. You can use a `Yeoman <http://yeoman.io/>`_ code generator, called
  35. `generator-conversejs <https://github.com/jcbrand/generator-conversejs>`_ to
  36. generate plugin scaffolding code, which you can use as a starting point and
  37. basis for writing your plugin.
  38. Please refer to the `generator-conversejs <https://github.com/jcbrand/generator-conversejs>`_
  39. README for information on how to use it.
  40. Registering a plugin
  41. --------------------
  42. Plugins need to be registered (and whitelisted) before they can be loaded and
  43. initialized.
  44. You register a converse.js plugin by calling ``converse.plugins.add``.
  45. The plugin itself is a JavaScript object which usually has at least an
  46. ``initialize`` method, which gets called at the end of the
  47. ``converse.initialize`` method which is the top-level method that gets called
  48. by the website to configure and initialize Converse.js itself.
  49. Here's an example code snippet:
  50. .. code-block:: javascript
  51. converse.plugins.add('myplugin', {
  52. initialize: function () {
  53. // This method gets called once converse.initialize has been called
  54. // and the plugin itself has been loaded.
  55. // Inside this method, you have access to the closured
  56. // _converse object as an attribute on "this".
  57. // E.g. this._converse
  58. },
  59. });
  60. .. note:: It's important that `converse.plugins.add` is called **before**
  61. `converse.initialize` is called. Otherwise the plugin will never get
  62. registered and never get called.
  63. Whitelisting of plugins
  64. -----------------------
  65. As of converse.js 3.0.0 and higher, plugins need to be whitelisted before they
  66. can be used. This is because plugins have access to a powerful API. For
  67. example, they can read all messages and send messages on the user's behalf.
  68. To avoid malicious plugins being registered (i.e. by malware infected
  69. advertising networks) we now require whitelisting.
  70. To whitelist a plugin simply means to specify :ref:`whitelisted_plugins` when
  71. you call ``converse.initialize``.
  72. Security and access to the inner workings
  73. -----------------------------------------
  74. The globally available ``converse`` object, which exposes the API methods, such
  75. as ``initialize`` and ``plugins.add``, is a wrapper that encloses and protects
  76. a sensitive inner object, named ``_converse`` (not the underscore prefix).
  77. This inner ``_converse`` object contains all the Backbone models and views,
  78. as well as various other attributes and functions.
  79. Within a plugin, you will have access to this internal
  80. `"closured" <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures>`_
  81. ``_converse`` object, which is normally not exposed in the global variable scope.
  82. The inner ``_converse`` object is made private in order to safely hide and
  83. encapsulate sensitive information and methods which should not be exposed
  84. to any 3rd-party scripts that might be running in the same page.
  85. Loading a plugin module
  86. -----------------------
  87. Converse.js uses the UMD (Universal Modules Definition) as its module syntax.
  88. This makes modules loadable via `require.js`, `webpack` or other module
  89. loaders, but also includable as old-school `<script>` tags in your HTML.
  90. Here's an example of the plugin shown above wrapped inside a UMD module:
  91. .. code-block:: javascript
  92. (function (root, factory) {
  93. if (typeof define === 'function' && define.amd) {
  94. // AMD. Register as a module called "myplugin"
  95. define("myplugin", ["converse"], factory);
  96. } else {
  97. // Browser globals. If you're not using a module loader such as require.js,
  98. // then this line below executes. Make sure that your plugin's <script> tag
  99. // appears after the one from converse.js.
  100. factory(converse);
  101. }
  102. }(this, function (converse) {
  103. converse.plugins.add('myplugin', {
  104. initialize: function () {
  105. // This method gets called once converse.initialize has been called
  106. // and the plugin itself has been loaded.
  107. // Inside this method, you have access to the closured
  108. // _converse object as an attribute on "this".
  109. // E.g. this._converse
  110. },
  111. });
  112. });
  113. Accessing 3rd party libraries
  114. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  115. Immediately inside the module shown above you can access 3rd party libraries (such
  116. moment, underscore and jQuery) via the ``converse.env`` map.
  117. The code for it would look something like this:
  118. .. code-block:: javascript
  119. // Commonly used utilities and variables can be found under the "env"
  120. // namespace of the "converse" global.
  121. var Strophe = converse.env.Strophe,
  122. $iq = converse.env.$iq,
  123. $msg = converse.env.$msg,
  124. $pres = converse.env.$pres,
  125. $build = converse.env.$build,
  126. b64_sha1 = converse.env.b64_sha1;
  127. $ = converse.env.jQuery,
  128. _ = converse.env._,
  129. moment = converse.env.moment;
  130. These dependencies are closured so that they don't pollute the global
  131. namespace, that's why you need to access them in such a way inside the module.
  132. Overrides
  133. ---------
  134. Plugins can override core code or code from other plugins. Refer to the full
  135. example at the bottom for code details.
  136. Use the ``overrides`` functionality with caution. It basically resorts to
  137. monkey patching which pollutes the call stack and can make your code fragile
  138. and prone to bugs when Converse.js gets updated. Too much use of ``overrides``
  139. is therefore a "code smell" which should ideally be avoided.
  140. A better approach is to listen to the events emitted by Converse.js, and to add
  141. your code in event handlers. This is however not always possible, in which case
  142. the overrides are a powerful tool.
  143. .. _`optional_dependencies`:
  144. Optional plugin dependencies
  145. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  146. When using ``overrides``, the code that you want to override (which is either
  147. in ``converse-core`` or in other plugins), needs to be loaded already by the
  148. type the ``overrides`` object is being parsed.
  149. So it's important to include overridden plugins in the AMD ``define`` statement
  150. at the top of the plugin module.
  151. However, sometimes you want to override parts of another plugin if it exists, but you
  152. don't want anything to break if it doesn't exist (for example when using a
  153. custom build which excludes that plugin). An example is the
  154. `converse-dragresize <https://github.com/jcbrand/converse.js/blob/master/src/converse-dragresize.js>`_
  155. plugin, which will add drag-resize handles to the headlines box (which shows
  156. messages of type ``headline``) but doesn't care if that particular plugin isn't
  157. actually loaded.
  158. In this case, you can't specify the plugin as a dependency in the ``define``
  159. statement at the top of the plugin, since it might not always be available,
  160. which would cause ``require.js`` to throw an error.
  161. To resolve this problem we have the ``optional_dependencies`` Array attribute.
  162. With this you can specify those dependencies which need to be loaded before
  163. your plugin, if they exist. If they don't exist, they won't be ignored.
  164. If the setting :ref:`strict_plugin_dependencies` is set to true,
  165. an error will be raised if the plugin is not found, thereby making them
  166. non-optional.
  167. Extending converse.js's configuration settings
  168. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  169. Converse.js comes with various :ref:`configuration-settings`_ that can be used to
  170. modify its functionality and behavior.
  171. All configuration settings have default values which can be overridden when
  172. `converse.initialize` (see :ref:`initialize`_) gets called.
  173. Plugins often need their own additional configuration settings and you can add
  174. these settings with the `_converse.api.settings.update` method (see
  175. :ref:`settings-update`_).
  176. Exposing promises
  177. ~~~~~~~~~~~~~~~~~
  178. Converse.js has a ``waitUntil`` API method (see :ref:`waituntil-grouping`_)
  179. which allows you to wait for various promises to resolve before executing a
  180. piece of code.
  181. You can add new promises for your plugin by calling
  182. ``_converse.api.promises.add`` (see :ref:`promises-grouping`_).
  183. Generally, your plugin will then also be responsible for making sure these
  184. promises are resolved. You do this by calling ``_converse.api.emit``, which not
  185. only resolves the plugin but will also emit an event with the same name.
  186. A full example plugin
  187. ---------------------
  188. .. code-block:: javascript
  189. (function (root, factory) {
  190. if (typeof define === 'function' && define.amd) {
  191. // AMD. Register as a module called "myplugin"
  192. define("<%= name %>", ["converse"], factory);
  193. } else {
  194. // Browser globals. If you're not using a module loader such as require.js,
  195. // then this line below executes. Make sure that your plugin's <script> tag
  196. // appears after the one from converse.js.
  197. factory(converse);
  198. }
  199. }(this, function (converse) {
  200. // Commonly used utilities and variables can be found under the "env"
  201. // namespace of the "converse" global.
  202. var Strophe = converse.env.Strophe,
  203. $iq = converse.env.$iq,
  204. $msg = converse.env.$msg,
  205. $pres = converse.env.$pres,
  206. $build = converse.env.$build,
  207. b64_sha1 = converse.env.b64_sha1;
  208. $ = converse.env.jQuery,
  209. _ = converse.env._,
  210. moment = converse.env.moment;
  211. // The following line registers your plugin.
  212. converse.plugins.add("<%= name %>", {
  213. /* Optional dependencies are other plugins which might be
  214. * overridden or relied upon, and therefore need to be loaded before
  215. * this plugin. They are called "optional" because they might not be
  216. * available, in which case any overrides applicable to them will be
  217. * ignored.
  218. *
  219. * NB: These plugins need to have already been loaded via require.js.
  220. *
  221. * It's possible to make optional dependencies non-optional.
  222. * If the setting "strict_plugin_dependencies" is set to true,
  223. * an error will be raised if the plugin is not found.
  224. */
  225. 'optional_dependencies': [],
  226. /* Converse.js's plugin mechanism will call the initialize
  227. * method on any plugin (if it exists) as soon as the plugin has
  228. * been loaded.
  229. */
  230. 'initialize': function () {
  231. /* Inside this method, you have access to the private
  232. * `_converse` object.
  233. */
  234. var _converse = this._converse;
  235. _converse.log("The <%= name %> plugin is being initialized");
  236. /* From the `_converse` object you can get any configuration
  237. * options that the user might have passed in via
  238. * `converse.initialize`. These values are stored in the
  239. * "user_settings" attribute.
  240. *
  241. * You can also specify new configuration settings for this
  242. * plugin, or override the default values of existing
  243. * configuration settings. This is done like so:
  244. */
  245. _converse.api.settings.update({
  246. 'initialize_message': 'Initializing <%= name %>!'
  247. });
  248. /* The user can then pass in values for the configuration
  249. * settings when `converse.initialize` gets called.
  250. * For example:
  251. *
  252. * converse.initialize({
  253. * "initialize_message": "My plugin has been initialized"
  254. * });
  255. *
  256. * And the configuration setting is then available via the
  257. * `user_settings` attribute:
  258. */
  259. alert(this._converse.user_settings.initialize_message);
  260. /* Besides `_converse.api.settings.update`, there is also a
  261. * `_converse.api.promises.add` method, which allows you to
  262. * add new promises that your plugin is obligated to fulfill.
  263. *
  264. * This method takes a string or a list of strings which
  265. * represent the promise names:
  266. *
  267. * _converse.api.promises.add('myPromise');
  268. *
  269. * Your plugin should then, when appropriate, resolve the
  270. * promise by calling `_converse.api.emit`, which will also
  271. * emit an event with the same name as the promise.
  272. * For example:
  273. *
  274. * _converse.api.emit('operationCompleted');
  275. *
  276. * Other plugins can then either listen for the event
  277. * `operationCompleted` like so:
  278. *
  279. * _converse.api.listen.on('operationCompleted', function { ... });
  280. *
  281. * or they can wait for the promise to be fulfilled like so:
  282. *
  283. * _converse.api.waitUntil('operationCompleted', function { ... });
  284. */
  285. },
  286. /* If you want to override some function or a Backbone model or
  287. * view defined elsewhere in converse.js, then you do that under
  288. * the "overrides" namespace.
  289. */
  290. 'overrides': {
  291. /* For example, the private *_converse* object has a
  292. * method "onConnected". You can override that method as follows:
  293. */
  294. 'onConnected': function () {
  295. // Overrides the onConnected method in converse.js
  296. // Top-level functions in "overrides" are bound to the
  297. // inner "_converse" object.
  298. var _converse = this;
  299. // Your custom code can come here ...
  300. // You can access the original function being overridden
  301. // via the __super__ attribute.
  302. // Make sure to pass on the arguments supplied to this
  303. // function and also to apply the proper "this" object.
  304. _converse.__super__.onConnected.apply(this, arguments);
  305. // Your custom code can come here ...
  306. },
  307. /* Override converse.js's XMPPStatus Backbone model so that we can override the
  308. * function that sends out the presence stanza.
  309. */
  310. 'XMPPStatus': {
  311. 'sendPresence': function (type, status_message, jid) {
  312. // The "_converse" object is available via the __super__
  313. // attribute.
  314. var _converse = this.__super__._converse;
  315. // Custom code can come here ...
  316. // You can call the original overridden method, by
  317. // accessing it via the __super__ attribute.
  318. // When calling it, you need to apply the proper
  319. // context as reference by the "this" variable.
  320. this.__super__.sendPresence.apply(this, arguments);
  321. // Custom code can come here ...
  322. }
  323. }
  324. }
  325. });
  326. }));