list
logo

Javascript API

Webswing provides an NPM module for easier integration of Webswing to javascript/typescript projects. This allows easier integration of Webswing into the existing web project. The module provides typescript declarations.

Requirements: This module works with Webswing 22.2 and newer.

Installation

npm install webswing-api

Basic Usage

import { getWebswingApi } from 'webswing-api'

getWebswingApi("http://localhost:8080/webswing-demo").then((api) => {
    api.bootstrap(document.getElementById('rootElement'))
})

The getWebswingApi function asynchronously loads the Webswing JavaScript client from the Webswing server identified by the connectionUrl parameter. When the client is loaded, it returns an API object that can bootstrap a Webswing view into a DOM element or create it in a detached state.

Usage with Customization and Options

import { getWebswingApi } from 'webswing-api'

const connectionUrl = "http://localhost:8080/webswing-demo"

getWebswingApi(connectionUrl, i18n).then((api) => {
    const instance = api.bootstrap(document.getElementById('rootElement'), {
            //here define basic bootstrap options like:
            autoStart: false,
            args: 'customArgs sent to Swing app',
            onReady: () => { instance.start()},
            onStart: () => {// ...}
        },
        (injector) => {
            // here define more advanced customizations of Webswing JS client behavior like dialog contents: 
            injector.services.dialog.content.startingDialog.content = `<p>MyApp is being started</p>`
            injector.services.dialog.content.initializingDialog.content = `<p>MyApp is being initialized</p>`
        }
    )
}).catch((e) => {
    console.error(e)
    // ...
})

The getWebswingApi function allows to pass in custom translations logic and with the bootstrap function you can modify the bootstrap options and also define advanced customizations of the Webswing client behavior.

Detached Instances

Pass null as the first argument of bootstrap to create an instance without attaching its content to the DOM. A non-null host is initialized normally even when it has not been inserted into the document yet. The instance starts automatically unless autoStart is set to false, and its connection and Swing session remain active while it is detached. Use setElement to attach the content when a host becomes available, and pass null again before a framework unmounts that host. Calling setElement(null) while the instance is already detached is a no-op.

import { getWebswingApi } from 'webswing-api'

const api = await getWebswingApi('http://localhost:8080/webswing-demo')
const instance = api.bootstrap(null)

// Attach the running instance.
instance.setElement(document.getElementById('rootElement'))

// Detach it while preserving the connection and Swing session.
instance.setElement(null)

// The same instance can later be attached to another host.
instance.setElement(document.getElementById('nextRootElement'))

getElement returns the host element currently associated with the instance. After setElement(null), that element no longer contains the Webswing content. Call destroy when the instance is no longer needed.

For a single-page application, keep the Webswing instance in an application-level service instead of a route component. Detach the instance before removing the current route's DOM, render the next route, and then attach it to the new host. A full page reload creates a new JavaScript context and cannot preserve the same instance.

Custom i18n

You can reuse the i18n framework from your project by passing custom translate logic as second parameter of getWebswingApi function. Otherwise will be loaded from server. The translation logic is expecting object with this interface:

interface ITranslations {
    translate: (key: string, vars?: any) => string;
    getLocale: () => string;
}

Bootstrap Options

Pass bootstrap options as the second argument of api.bootstrap(element, options, customization).

JavaScript API options

Supply these options in JavaScript. They are not available in Admin Console -> application web configuration -> Javascript Bootstrap Options. Not set means the option is omitted unless your integration supplies it.

Name Description Default value Type
accessibilityDisabledByOverride Initial client accessibility override. Replaced by the application's accessibility setting when instance configuration is received from the server. Server configuration boolean
actions Handlers for actions sent by the Swing application, keyed by action name. Each handler receives an IWebActionEvent; action calls may return a string, Uint8Array, or a Promise resolving to either value or no value. Not set object
args Custom application arguments sent to the server. Available as ${customArgs} in application configuration; configure the launcher arguments to pass them to the Swing application. Not set string
autoStart Start the application automatically after initialization. The JavaScript API defaults to true; set to false and call instance.start() manually to control startup. true (JavaScript API) boolean
clientId Target application instance ID for advanced mirror integrations. Normal application sessions manage the instance ID automatically. Not set string
connectionUrl Application URL used to connect to Webswing. The JavaScript API supplies the URL passed to getWebswingApi. URL passed to getWebswingApi string
debugPort Port requested for remote debugging of the Swing application. Requires debugging support in the server configuration. Not set number
filesListener File-transfer callbacks: directTransferDownloadProgressAll, directTransferDownloadAllDone, directTransferDownloadDone, directTransferDownloadFailed, fileUploadProgressAll, fileUploadDone, fileUploadFailed, and handleError. Not set object
linkedViewId Encoded Linked View ID used to join an existing application session. Obtain a valid Linked View URL from WebswingApi.getLinkedViewUrl() rather than constructing the ID manually. Not set string
linkedViewName Name for the new Linked View, reported to application listeners. Not set string
mapEscapeShortcutSequence Keyboard shortcuts that start an escape sequence. Each entry contains a shortcut (KeyShortcut) and a sequence (EscapeSequence, with timeoutMs and a mappings map of key codes to shortcuts). Not set array
mapKeyShortcut Keyboard shortcut remappings. Each entry contains a source shortcut and target mapping, both KeyShortcut objects with key or keyCode and modifiers (alt, ctrl, meta, shift). Not set array
mirrorConnectionUrl Alternative connection URL for mirror mode. connectionUrl string
mirrorMode Enable mirror mode for viewing an existing application instance. Live mirroring requires the mirror authentication callbacks below. false boolean
mirrorSuffixCallback Callback returning a Promise with the administrator security suffix used to authenticate live mirroring. Not set () => Promise<string>
mirrorTokenCallback Callback returning a Promise with the administrator token used to authenticate live mirroring. Not set () => Promise<string>
multiScreenSupportEnabled Initial client multi-screen flag. Replaced by the application's multi-screen setting when instance configuration is received from the server. Server configuration boolean
onDisconnected Called when the WebSocket connection closes or fails. The Swing application may still be running on the server. Not set () => void
onReady Called after client initialization and successful login, before automatic startup. Receives the Webswing instance API; with autoStart: false, call instance.start() when ready. Not set (instance: IWebswingInstance) => void
onShutdown Called when the client handles an application shutdown notification from the server. Not set () => void
onStart Called when the client connects to the Swing application, including reconnections. Not set () => void
pingParams Legacy network-quality settings object with count, interval, maxLatency, notifyIf, and optional url. Prefer pingCount, pingInterval, pingMaxLatency, pingNotifyIf, and pingUrl. Not set object
realm Authentication realm passed to security modules that support multiple realms. Not set string
recording Request session recording when connecting to the application. Requires recording to be allowed by the server configuration. Not set boolean
recordingFile Recording file to replay locally. Enables recording playback and mirror mode instead of starting a live application session. Not set File or Blob
securityToken Token passed to the configured security module during login. Its meaning depends on the security module. Not set string
testMode Advanced test integration flag that suppresses automatic logout when the application shuts down. Not set boolean
undockConnectionUrl Alternative application URL used for undocked browser windows. connectionUrl string
uploadDirectories Reserved client option. Directory-upload availability is supplied by the server's file-dialog configuration. Not set boolean

Server-configurable options

See the server-configurable bootstrap options for settings available in Admin Console -> application web configuration -> Javascript Bootstrap Options. You can also pass these settings in the JavaScript bootstrap options object; JavaScript values override the server settings.

Javascript Bootstrap Options

Webswing Instance API Reference

api.bootstrap will return an instance of webswing object with a set of functions. Check the reference below.

Methods Description
start This initiates the connection to Webswing server and starts the Swing application. If autoStart is false, call this function manually. When autoStart is omitted, the API defaults it to true and starts automatically.
disconnect Disconnects the current Webswing session, but leaving the swing application running.
configure Configure instance options before start.
kill Disconnects the current Webswing session with stopping the swing application.
destroy Destroys the Webswing instance to the state before bootstrapping the HTML div.
setControl Enables/disables the control of application. If set to false, no user events are sent to the Swing application.
repaint Notify webswing server that the application needs repaint.
instanceId Returns current instance id.
performAction Perform an action that triggers server-side listener.
callAction Call an action that triggers server-side listener. This call returns a Promise with call result.
logout Disconnects the current Webswing session and logs user out.
getConnectionInfo Get information about this instance's connection to server.
isUndocked Returns true if this script is running in an undocked instance
getFilesManager Get extended API for managing files.
getElement Returns the host element currently associated with the instance. When detached, the host does not contain the Webswing content.
setElement Attaches the instance content to an HTMLElement, or detaches it while preserving the connection when passed null.