Scripting environment

The scripting context

The embedded scripting engine runs scripts in a scripting context. There is only one context for all scripts in JOSM. It is initialized when the Scripting Plugins starts up and destroyed when JOSM is terminated. It is is populated with the following two objects:

josm
This global object represents the running JOSM instance.
require()
require() is a global function to load CommonJS modules.

Loading and using provided modules

The embedded scripting engine can load CommonJS-compatible modules.

Here's an example scripts which loads the built built in module josm/util.

var util = require("josm/util");
util.println("Hello world!");

Implementing and using custom modules

You can implement and use your own modules. Here's an example of a simple CommonJS-module which exports the function sayHello().

// file: helloworld.js
(function() {
exports.sayHello = function() {
    java.lang.System.out.println("Hello world!");
};
}());

A client script can load and use the module. Here's an example:

var hello = require("helloworld");
hello.sayHello();

The places, where the Scripting Plugin is looking for modules, can be configured in the preferences. It looks for modules in two places:

  1. First, it tries to load modules from the plugin jar file in the directory /js.
  2. Then, it tries to load it from one of the configured plugin repositories. Each repository is either a directory in the local file system or in jar/zip file in the local filesystem.

The start module

There is a special module ScriptingPluginStart which, if present, is loaded automatically when the Scripting Plugin starts. The following templates shows, that this plugin can export two functions which will be invoked by JOSM on startup and when the map frame changes.

The default location of this module is in $JOSM_HOME/plugins/scripting/modules.

// file: ScriptingPlugin_Start.js
exports.onStart = function() {
    /* 
     * add code to execute when the plugin is loaded
     */  
};

exports.onMapFrameChanged = function(oldframe, newframe) {
	/* 
	 * add code to execute when the the map frame changes, i.e. when the UI
	 * switches from the welcome pages to the layer view and vice versa
	 */
};
}());