### Install noVNC from Source
Source: https://github.com/replit/novnc/blob/master/_autodocs/INTEGRATION_GUIDE.md
Clone the noVNC repository, navigate to the directory, and install dependencies and build the project from source.
```bash
git clone https://github.com/novnc/noVNC.git
cd noVNC
npm install
npm run build
```
--------------------------------
### Install noVNC from Snap
Source: https://github.com/replit/novnc/blob/master/README.md
Installs the latest release of noVNC from the Snap store. This is the primary method for getting noVNC on systems that support Snap.
```bash
sudo snap install novnc
```
--------------------------------
### RFB Connection Example
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/rfb.md
Example demonstrating how to create a new RFB instance, connect to a VNC server using a WebSocket URL, and listen for connection and disconnection events. Ensure the target DOM element exists and the WebSocket URL is correct.
```javascript
import RFB from './core/rfb.js';
// Connect with WebSocket URL
const rfb = new RFB(
document.getElementById('vnc-container'),
'ws://vnc-server.example.com:6080',
{
shared: true,
credentials: {
username: 'user',
password: 'pass'
}
}
);
// Listen for connection
rfb.addEventListener('connect', () => {
console.log('Connected to remote desktop');
});
// Listen for disconnection
rfb.addEventListener('disconnect', (e) => {
console.log('Disconnected:', e.detail.clean);
});
```
--------------------------------
### Example Usage of Credentials Object
Source: https://github.com/replit/novnc/blob/master/_autodocs/types.md
Demonstrates how to create and use a Credentials object with the sendCredentials method.
```javascript
const credentials = {
username: 'admin',
password: 'secretpassword',
target: 'vm-001'
};
rfb.sendCredentials(credentials);
```
--------------------------------
### Install noVNC via npm
Source: https://github.com/replit/novnc/blob/master/_autodocs/INTEGRATION_GUIDE.md
Use this command to install the noVNC library as an npm package in your project.
```bash
npm install @replit/novnc
```
--------------------------------
### Create a New noVNC Service
Source: https://github.com/replit/novnc/blob/master/README.md
Configures and starts a new noVNC service that listens on a specified port and connects to a VNC server. Services defined with 'snap set' are automatically started.
```bash
sudo snap set novnc services.n6082.listen=6082 services.n6082.vnc=localhost:5902
```
--------------------------------
### Simple noVNC Client Setup
Source: https://github.com/replit/novnc/blob/master/_autodocs/INTEGRATION_GUIDE.md
Initializes an RFB client instance and attaches event listeners for connection and disconnection events.
```javascript
import RFB from './core/rfb.js';
const rfb = new RFB(
document.getElementById('vnc-container'),
'ws://vnc-server.example.com:6080'
);
rfb.addEventListener('connect', () => {
console.log('Connected!');
});
rfb.addEventListener('disconnect', (e) => {
console.log('Disconnected');
});
```
--------------------------------
### Run noVNC Directly
Source: https://github.com/replit/novnc/blob/master/README.md
Starts an instance of noVNC listening on a specified port and connecting to a VNC server. Ensure /snap/bin is in your PATH or use the full path to the novnc executable.
```bash
novnc --listen 6081 --vnc localhost:5901 # /snap/bin/novnc if /snap/bin is not in your PATH
```
--------------------------------
### Example Usage of RFB Options Object
Source: https://github.com/replit/novnc/blob/master/_autodocs/types.md
Illustrates how to instantiate the RFB class with various configuration options, such as disabling shared connections and providing initial credentials.
```javascript
new RFB(target, url, {
shared: false,
credentials: {
username: 'user',
password: 'pass'
},
wsProtocols: ['binary'],
repeaterID: 'repeater-123'
});
```
--------------------------------
### Launch noVNC with VNC Server
Source: https://github.com/replit/novnc/blob/master/README.md
Use the launch script to automatically download and start websockify, which includes a mini-webserver and the WebSockets proxy. The --vnc option specifies the location of a running VNC server.
```bash
./utils/launch.sh --vnc localhost:5901
```
--------------------------------
### Start Flash Policy Server with socat
Source: https://github.com/replit/novnc/blob/master/docs/flash_policy.txt
This command starts a socat process that listens on TCP port 843. It serves a cross-domain policy XML file to any connecting client, allowing Flash applications to connect to other domains.
```bash
DATA="echo '
'"
/usr/bin/socat -T 1 TCP-L:843,reuseaddr,fork,crlf SYSTEM:"$DATA"
```
--------------------------------
### Display Constructor
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/display.md
Initializes a new Display instance to render the remote VNC desktop onto a specified HTML canvas element. It handles the setup for canvas operations, viewport management, and image rendering, supporting scaling and clipping.
```APIDOC
## new Display(target)
### Description
Creates a new Display instance for rendering to a canvas element.
### Method
Constructor
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **target** (HTMLCanvasElement) - Required - Canvas element to render the remote desktop to
### Request Example
```javascript
import Display from './core/display.js';
const canvas = document.getElementById('vnc-canvas');
const display = new Display(canvas);
```
### Response
#### Success Response
- Display instance
### Throws
- Error: target is not specified
- Error: target is a string instead of DOM element
- Error: target does not have getContext method
```
--------------------------------
### Process Incoming WebSocket Messages
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/websock.md
This example demonstrates how to process incoming data by repeatedly shifting bytes from the receive queue when a 'message' event is fired.
```javascript
sock.on('message', () => {
while (sock.rQlen > 0) {
const byte = sock.rQshift8();
}
});
```
--------------------------------
### EventTargetMixin Class Example
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/utilities.md
Demonstrates how to use the EventTargetMixin to add event handling capabilities to a custom class. Import the mixin and extend it, then use addEventListener and dispatchEvent.
```javascript
import EventTargetMixin from './core/util/eventtarget.js';
class MyClass extends EventTargetMixin {
constructor() {
super();
}
}
const obj = new MyClass();
obj.addEventListener('myevent', (e) => {
console.log('Event:', e.detail);
});
obj.dispatchEvent(new CustomEvent('myevent', {
detail: { message: 'Hello' }
}));
```
--------------------------------
### Keyboard Input Handling and Event Emission
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/utilities.md
Demonstrates the setup of the Keyboard class for handling keyboard input and sending key events to an RFB server. It includes methods for grabbing and ungrabbing keyboard focus.
```javascript
import Keyboard from './core/input/keyboard.js';
const keyboard = new Keyboard(canvas);
keyboard.onkeyevent = (keysym, code, down) => {
// Send to server
};
keyboard.grab();
keyboard.ungrab();
```
--------------------------------
### Use Logging Functions and Get Configuration
Source: https://github.com/replit/novnc/blob/master/_autodocs/configuration.md
Utilize logging functions to record messages at different levels and retrieve the current logging configuration. Enable debug logging during development for detailed output.
```javascript
// Enable debug logging during development
Log.initLogging('debug');
// Use logging functions
Log.Debug("Detailed debug message");
Log.Info("General information");
Log.Warn("Warning message");
Log.Error("Error message");
// Get current logging configuration
const config = Log.getLogging();
```
--------------------------------
### Get Display Height
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/display.md
Access the read-only 'height' property to get the height of the remote desktop framebuffer in pixels.
```javascript
const displayHeight = display.height;
```
--------------------------------
### Basic Display Rendering
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/display.md
Initialize a Display instance, resize it to match the remote desktop dimensions, draw a solid color rectangle, and then flush the rendering to the canvas. Ensure the canvas element and Display class are available.
```javascript
import Display from './core/display.js';
const canvas = document.getElementById('vnc-canvas');
const display = new Display(canvas);
// Resize to match remote desktop
display.resize(1920, 1080);
// Draw a solid color rectangle
display.fillRect(100, 100, 200, 150, {r: 0, g: 0, b: 255});
// Flush rendering
display.flush();
```
--------------------------------
### Get Display Width
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/display.md
Access the read-only 'width' property to get the width of the remote desktop framebuffer in pixels.
```javascript
const displayWidth = display.width;
```
--------------------------------
### Get Logging Configuration
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/utilities.md
Retrieves the current logging configuration object.
```javascript
const config = Log.getLogging();
```
--------------------------------
### rQslice(start, end)
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/websock.md
Returns a view of the receive queue without modifying the read index.
```APIDOC
## rQslice(start, end)
### Description
Returns a view of the receive queue without modifying the read index.
### Method
`sock.rQslice(start[, end])`
### Parameters
#### Path Parameters
- **start** (number) - Required - Start offset from current read position
- **end** (number) - Optional - End offset from current read position
### Returns
`Uint8Array` - View of queue data
### Example
```javascript
// Peek at next 4 bytes without consuming
const header = sock.rQslice(0, 4);
```
```
--------------------------------
### Establish Websock Connection and Handle Events
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/websock.md
Connect to a WebSocket server and set up listeners for 'open', 'message', and 'close' events. Ensure the 'open' event is handled to confirm connection before sending data.
```javascript
import Websock from './core/websock.js';
const sock = new Websock();
sock.on('open', () => {
console.log('Connected');
});
sock.on('message', () => {
// Process available data
while (sock.rQlen >= 4) {
const value = sock.rQshift32();
console.log('Received:', value);
}
});
sock.on('close', (e) => {
console.log('Closed');
});
sock.open('ws://example.com:6080');
```
--------------------------------
### Connect to VNC Server with noVNC
Source: https://github.com/replit/novnc/blob/master/vnc_lite.html
This snippet shows how to initialize and connect to a VNC server using the RFB module. It handles connection parameters like host, port, password, and path, and sets up event listeners for connection status and authentication.
```javascript
// RFB holds the API to connect and communicate with a VNC server
import RFB from './core/rfb.js';
let rfb;
let desktopName;
// When this function is called we have // successfully connected to a server
function connectedToServer(e) {
status("Connected to " + desktopName);
}
// This function is called when we are disconnected
function disconnectedFromServer(e) {
if (e.detail.clean) {
status("Disconnected");
} else {
status("Something went wrong, connection is closed");
}
}
// When this function is called, the server requires // credentials to authenticate
function credentialsAreRequired(e) {
const password = prompt("Password Required:");
rfb.sendCredentials({ password: password });
}
// When this function is called we have received // a desktop name from the server
function updateDesktopName(e) {
desktopName = e.detail.name;
}
// Since most operating systems will catch Ctrl+Alt+Del // before they get a chance to be intercepted by the browser, // we provide a way to emulate this key sequence.
function sendCtrlAltDel() {
rfb.sendCtrlAltDel();
return false;
}
// Show a status text in the top bar
function status(text) {
document.getElementById('status').textContent = text;
}
// This function extracts the value of one variable from the // query string. If the variable isn't defined in the URL // it returns the default value instead.
function readQueryVariable(name, defaultValue) {
// A URL with a query parameter can look like this:
// https://www.example.com?myqueryparam=myvalue
//
// Note that we use location.href instead of location.search // because Firefox < 53 has a bug w.r.t location.search
const re = new RegExp('.*\[?&\]' + name + '=(\[^\]\[)
'), match = document.location.href.match(re);
if (match) {
// We have to decode the URL since want the cleartext value
return decodeURIComponent(match[1]);
}
return defaultValue;
}
document.getElementById('sendCtrlAltDelButton')
.onclick = sendCtrlAltDel;
// Read parameters specified in the URL query string
// By default, use the host and port of server that served this file
const host = readQueryVariable('host', window.location.hostname);
let port = readQueryVariable('port', window.location.port);
const password = readQueryVariable('password');
const path = readQueryVariable('path', 'websockify');
// | | | | | |
// | | | Connect | | |
// v v v v v v
status("Connecting");
// Build the websocket URL used to connect
let url;
if (window.location.protocol === "https:") {
url = 'wss';
} else {
url = 'ws';
}
url += '://' + host;
if(port) {
url += ':' + port;
}
url += '/' + path;
// Creating a new RFB object will start a new connection
rfb = new RFB(document.getElementById('screen'), url, {
credentials: {
password: password
}
});
// Add listeners to important events from the RFB module
rfb.addEventListener("connect", connectedToServer);
rfb.addEventListener("disconnect", disconnectedFromServer);
rfb.addEventListener("credentialsrequired", credentialsAreRequired);
rfb.addEventListener("desktopname", updateDesktopName);
// Set parameters that can be changed on an active connection
rfb.viewOnly = readQueryVariable('view_only', false);
rfb.scaleViewport = readQueryVariable('scale', false);
```
--------------------------------
### Get Raw Encoding ID
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/decoders.md
Retrieves the encoding ID for the Raw encoding. This is the baseline uncompressed encoding.
```javascript
import { encodings } from './core/encodings.js';
console.log(encodings.encodingRaw); // 0
```
--------------------------------
### Basic HTML Structure for noVNC
Source: https://github.com/replit/novnc/blob/master/_autodocs/INTEGRATION_GUIDE.md
Sets up the basic HTML document with a container for the VNC display and a script tag to import the RFB module.
```html
VNC Client
```
--------------------------------
### Keyboard Helper Functions
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/utilities.md
Provides functions to get keyboard event details like keycode, character, and RFB keysym.
```APIDOC
## Keyboard Utilities
### Description
Provides helper functions for keyboard events.
### Functions
- `getKeycode(event)` - Get physical key code
- `getKey(event)` - Get character for key
- `getKeysym(event)` - Get RFB keysym value
```
--------------------------------
### Encodings Constants
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/utilities.md
Constants for VNC encoding types, including standard and pseudo-encodings, and a utility function to get encoding names.
```APIDOC
## Encoding Constants
### Description
Constants for VNC encoding types.
### Constants
#### Standard Encodings
- `encodings.encodingRaw` (Number) - 0
- `encodings.encodingCopyRect` (Number) - 1
- `encodings.encodingRRE` (Number) - 2
- `encodings.encodingHextile` (Number) - 5
- `encodings.encodingTight` (Number) - 7
- `encodings.encodingTightPNG` (Number) - -260
#### Pseudo-Encodings (Capabilities)
- `encodings.pseudoEncodingQualityLevel9`
- `encodings.pseudoEncodingDesktopSize`
- `encodings.pseudoEncodingCursor`
- `encodings.pseudoEncodingQEMUExtendedKeyEvent`
- `encodings.pseudoEncodingDesktopName`
- `encodings.pseudoEncodingXvp`
- `encodings.pseudoEncodingFence`
- `encodings.pseudoEncodingContinuousUpdates`
- `encodings.pseudoEncodingExtendedClipboard`
- `encodings.pseudoEncodingReplitAudio`
### Functions
- `encodingName(encodingType)` - Returns the human-readable name for a given encoding type.
### Example Usage
```javascript
import { encodings, encodingName } from './core/encodings.js';
// Standard encodings
console.log(encodings.encodingRaw); // 0
// Pseudo-encodings
console.log(encodings.pseudoEncodingDesktopSize);
// Get human-readable encoding name
const name = encodingName(7); // Returns 'Tight'
console.log(name);
```
```
--------------------------------
### RFB Constructor Options
Source: https://github.com/replit/novnc/blob/master/_autodocs/configuration.md
Initialize the RFB client with various configuration options. The 'shared' option defaults to true, allowing multiple clients. 'credentials' can be provided upfront. 'repeaterID' is for routing through a VNC repeater. 'wsProtocols' are for WebSocket negotiation. 'showDotCursor' is deprecated.
```javascript
new RFB(target, urlOrChannel, {
shared: true,
credentials: { username: '', password: '', target: '' },
repeaterID: '',
wsProtocols: [],
showDotCursor: false
})
```
--------------------------------
### Get CopyRect Encoding ID
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/decoders.md
Retrieves the encoding ID for the CopyRect encoding. This encoding is efficient for animations and window moves.
```javascript
import { encodings } from './core/encodings.js';
console.log(encodings.encodingCopyRect); // 1
```
--------------------------------
### RFB Connection with Options
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/rfb.md
Connects to a VNC server with custom options, including shared mode and credentials. Also demonstrates setting properties like scaleViewport, clipViewport, qualityLevel, and compressionLevel.
```javascript
const rfb = new RFB(
document.getElementById('screen'),
'ws://vnc.example.com:6080',
{
shared: false,
credentials: { username: 'user', password: 'pass' }
}
);
rfb.scaleViewport = true;
rfb.clipViewport = false;
rfb.qualityLevel = 8;
rfb.compressionLevel = 2;
```
--------------------------------
### RFB Default Configuration
Source: https://github.com/replit/novnc/blob/master/_autodocs/configuration.md
Illustrates the default configuration when creating an RFB instance without explicit options. Shows equivalent settings for constructor parameters and default property values.
```javascript
const rfb = new RFB(target, url);
// Equivalent to:
const rfb = new RFB(target, url, {
shared: true,
credentials: {},
repeaterID: '',
wsProtocols: [],
showDotCursor: false
});
// Default property values:
rfb.viewOnly = false;
rfb.clipViewport = false;
rfb.scaleViewport = false;
rfb.dragViewport = false;
rfb.focusOnClick = true;
rfb.resizeSession = false;
rfb.showDotCursor = false;
rfb.background = 'rgb(40, 40, 40)';
rfb.qualityLevel = 6;
rfb.compressionLevel = 2;
// Default Display configuration:
display.scale = 1.0;
display.clipViewport = false;
```
--------------------------------
### Get Tight Encoding ID
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/decoders.md
Retrieves the encoding ID for the Tight encoding. This encoding provides excellent compression, especially with JPEG.
```javascript
import { encodings } from './core/encodings.js';
console.log(encodings.encodingTight); // 7
```
--------------------------------
### Initialize and Use Debug Logging
Source: https://github.com/replit/novnc/blob/master/_autodocs/errors.md
Initialize logging to a specific level, such as 'debug', during development. Use the provided logging functions (Debug, Info, Warn, Error) to output detailed information. You can also retrieve the current logging configuration.
```javascript
import * as Log from './core/util/logging.js';
// During development
Log.initLogging('debug');
Log.Debug('Detailed debug information');
Log.Info('General information');
Log.Warn('Warnings');
Log.Error('Errors');
// Get current logging state
const config = Log.getLogging();
```
--------------------------------
### Get Encoding Name by ID
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/decoders.md
Converts an encoding ID number to its human-readable string name. Handles known and unknown encoding IDs.
```javascript
import { encodingName } from './core/encodings.js';
console.log(encodingName(0)); // "Raw"
console.log(encodingName(7)); // "Tight"
console.log(encodingName(-260)); // "TightPNG"
console.log(encodingName(999)); // "[unknown encoding 999]"
```
--------------------------------
### Initialize Logging
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/utilities.md
Initializes the logging system with a specific log level. Available levels are 'debug', 'info', 'warn', and 'error'.
```javascript
import * as Log from './core/util/logging.js';
Log.initLogging('debug');
```
--------------------------------
### Get RRE Encoding ID
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/decoders.md
Retrieves the encoding ID for the RRE (Rise and Run Length Encoding). This encoding is efficient for solid-color regions.
```javascript
import { encodings } from './core/encodings.js';
console.log(encodings.encodingRRE); // 2
```
--------------------------------
### RFB.audioCodecs Audio Codec Identifiers
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/rfb.md
Object containing identifiers for supported audio codecs. Examples include Opus in WebM container and MP3.
```javascript
RFB.audioCodecs.OpusWebM // Opus codec in WebM container
RFB.audioCodecs.MP3 // MP3 codec
```
--------------------------------
### Enable Audio with Codec Configuration
Source: https://github.com/replit/novnc/blob/master/_autodocs/types.md
Demonstrates how to enable audio streams using the `enableAudio` method, specifying the channel, audio codec, and bitrate. Supports Opus in WebM and MP3 codecs.
```javascript
rfb.enableAudio(2, RFB.audioCodecs.OpusWebM, 128);
rfb.enableAudio(1, RFB.audioCodecs.MP3, 96);
```
--------------------------------
### RFB.cursors Predefined Cursor Images
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/rfb.md
Access predefined cursor images used internally for rendering. Examples include 'none', 'default', and 'pointer'.
```javascript
RFB.cursors.none
RFB.cursors.default
RFB.cursors.pointer
// etc.
```
--------------------------------
### Basic Rendering
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/display.md
Demonstrates the basic usage of the Display API for rendering content onto a canvas, including resizing, drawing rectangles, and flushing changes.
```APIDOC
## Basic Rendering
### Description
Provides a basic example of how to initialize and use the Display API for rendering.
### Usage
```javascript
import Display from './core/display.js';
const canvas = document.getElementById('vnc-canvas');
const display = new Display(canvas);
// Resize to match remote desktop
display.resize(1920, 1080);
// Draw a solid color rectangle
display.fillRect(100, 100, 200, 150, {r: 0, g: 0, b: 255});
// Flush rendering
display.flush();
```
```
--------------------------------
### Manage Receive Queue Read Index
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/websock.md
Set or get the current read index in the receive queue. Reset the read position by setting it to 0.
```javascript
sock.rQi = 0; // Reset read position
const position = sock.rQi;
```
--------------------------------
### Configure Display Properties
Source: https://github.com/replit/novnc/blob/master/_autodocs/configuration.md
Initialize and configure display settings such as size, scaling, and viewport clipping. Ensure the canvas element is available before initializing Display.
```javascript
import Display from './core/display.js';
const display = new Display(canvas);
// Set initial size
display.resize(1920, 1080);
// Scale to 75%
display.scale = 0.75;
// Enable viewport clipping
display.clipViewport = true;
display.viewportChangeSize(1024, 768);
// Pan viewport
display.viewportChangePos(100, 50);
```
--------------------------------
### Get TightPNG Encoding ID
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/decoders.md
Retrieves the encoding ID for the TightPNG encoding. This variant uses PNG compression for better results with natural images.
```javascript
import { encodings } from './core/encodings.js';
console.log(encodings.encodingTightPNG); // -260
```
--------------------------------
### Get Hextile Encoding ID
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/decoders.md
Retrieves the encoding ID for the Hextile encoding. This encoding offers a good balance of efficiency and speed for general-purpose use.
```javascript
import { encodings } from './core/encodings.js';
console.log(encodings.encodingHextile); // 5
```
--------------------------------
### Configuration Options
Source: https://github.com/replit/novnc/blob/master/_autodocs/INDEX.md
Details the various configuration options available for the RFB constructor and other components, along with their usage patterns.
```APIDOC
## Configuration Options
### Description
Explains the parameters and properties used to configure noVNC's behavior.
### RFB Constructor Options
- **`url`** (string): WebSocket URL for the VNC server.
- **`credentials`** (object): `{ username, password }` for authentication.
- **`grabKeyboard`** (boolean): Whether to grab keyboard input.
- **`captureElement`** (HTMLElement): Element to capture mouse events.
- **`ws`** (WebSocket): Pre-existing WebSocket instance.
### RFB Runtime Properties
- **`viewOnly`** (boolean): Read-only mode.
- **`clipViewport`** (boolean): Clip rendering to viewport.
- **`scaleViewport`** (boolean): Scale viewport to fit.
- **`local_cursor`** (boolean): Use local cursor.
### Display Configuration
- **`width`**, **`height`**: Initial display dimensions.
- **`scale`**: Initial scaling factor.
### Logging Configuration
- **`level`** (string): Logging level (e.g., 'info', 'warn', 'error').
```
--------------------------------
### Provide Credentials (RFB)
Source: https://github.com/replit/novnc/blob/master/_autodocs/configuration.md
Configure initial authentication credentials including username, password, and target. The server may request additional credentials via the 'credentialsrequired' event if not fully provided.
```javascript
const rfb = new RFB(target, url, {
credentials: {
username: 'admin',
password: 'secretpassword',
target: 'vm-01'
}
});
// Only provide some credentials
const rfb2 = new RFB(target, url, {
credentials: {
password: 'mypassword'
}
});
// Server can request additional credentials via 'credentialsrequired' event
rfb.addEventListener('credentialsrequired', (e) => {
rfb.sendCredentials({
username: 'user2',
password: 'pass2'
});
});
```
--------------------------------
### Initialize Logging Levels
Source: https://github.com/replit/novnc/blob/master/_autodocs/configuration.md
Initialize the logging system with a specific log level. Choose the level based on the environment; 'debug' for development and 'warn' or 'error' for production.
```javascript
import * as Log from './core/util/logging.js';
// Set log level
Log.initLogging('debug'); // Show all messages
Log.initLogging('info'); // Info, warn, error
Log.initLogging('warn'); // Warn, error only
Log.initLogging('error'); // Error only
```
--------------------------------
### Instantiate Websock Class
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/websock.md
Creates a new Websock instance. Use this to initiate WebSocket or RTCDataChannel communication.
```javascript
new Websock()
```
```javascript
import Websock from './core/websock.js';
const sock = new Websock();
sock.on('message', () => {
// Data available in receive queue
});
sock.open('ws://server.example.com:6080');
```
--------------------------------
### Set and Get Display Scale
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/display.md
Control the scaling factor of the displayed content using the 'scale' property. Set to values like 0.75 for 75% or 1.5 for 150%.
```javascript
display.scale = 0.75; // Display at 75% size
display.scale = 1.5; // Display at 150% size
const currentScale = display.scale;
```
--------------------------------
### Accessing Keysym Values with KeyTable
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/utilities.md
Demonstrates how to access XFree86 keysym values for various keys using the KeyTable object. Import is required.
```javascript
import KeyTable from './core/input/keysym.js';
KeyTable.XK_a; // Keysym for 'a'
KeyTable.XK_Return; // Enter key
KeyTable.XK_Escape; // Escape key
KeyTable.XK_Control_L; // Left Control
KeyTable.XK_Alt_L; // Left Alt
KeyTable.XK_Super_L; // Windows/Command key
```
--------------------------------
### Set and Get Clip Viewport
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/display.md
Toggle clipping of the display to the visible viewport using the 'clipViewport' property. Set to 'true' to enable clipping and show scrollbars, or 'false' to disable.
```javascript
display.clipViewport = true; // Enable clipping
display.clipViewport = false; // Disable clipping
```
--------------------------------
### Full RFB Configuration with Runtime Options
Source: https://github.com/replit/novnc/blob/master/_autodocs/configuration.md
Configure a secure RFB connection with detailed options including credentials, WebSocket protocols, and repeater ID. Set runtime behaviors like viewport scaling, quality, and focus.
```javascript
const rfb = new RFB(
document.getElementById('screen'),
'wss://secure.example.com/vnc',
{
shared: false,
credentials: {
username: 'admin',
password: 'securepass',
target: 'workstation-1'
},
wsProtocols: ['binary'],
repeaterID: ''
}
);
// Configure runtime behavior
rfb.scaleViewport = true;
rfb.resizeSession = true;
rfb.qualityLevel = 8;
rfb.compressionLevel = 2;
rfb.focusOnClick = true;
rfb.viewOnly = false;
// Setup event handlers
rfb.addEventListener('connect', () => {
console.log('Connected');
});
rfb.addEventListener('credentialsrequired', (e) => {
if (e.detail.types.includes('password')) {
rfb.sendCredentials({ password: prompt('Password:') });
}
});
```
--------------------------------
### Configure Production VNC Settings
Source: https://github.com/replit/novnc/blob/master/_autodocs/INTEGRATION_GUIDE.md
Use this configuration for production deployments to set logging levels, authentication, and optimize performance. Set `viewOnly` to `true` for most users.
```javascript
// production-config.js
import RFB from './core/rfb.js';
import * as Log from './core/util/logging.js';
// Use production log level
Log.initLogging('error'); // Only show errors
const rfb = new RFB(container, productionServerUrl, {
shared: false, // Don't allow sharing
credentials: authToken, // Provide pre-auth token
wsProtocols: ['binary'] // Use binary protocol
});
// Only allow view-only or specific operations
rfb.viewOnly = true; // Most users: read-only
// rfb.viewOnly = false; // Admin users: read-write
// Optimize for production
rfb.qualityLevel = 6; // Balanced quality
rfb.compressionLevel = 5; // Moderate compression
rfb.focusOnClick = false; // Don't auto-focus
```
--------------------------------
### Adjust Quality vs Bandwidth
Source: https://github.com/replit/novnc/blob/master/_autodocs/README.md
Configure `qualityLevel` and `compressionLevel` to balance visual quality and bandwidth usage. Higher quality uses more bandwidth, while higher compression uses more CPU.
```javascript
// High quality (low compression)
rfb.qualityLevel = 9;
rfb.compressionLevel = 1;
// Low quality (high compression)
rfb.qualityLevel = 0;
rfb.compressionLevel = 9;
```
--------------------------------
### Parse Custom Protocol Messages
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/websock.md
Implement custom message parsing logic within the 'message' event handler. This example demonstrates reading a message type and length before processing the data.
```javascript
sock.on('message', () => {
if (sock.rQlen < 1) return;
const messageType = sock.rQpeek8();
switch (messageType) {
case 0:
if (sock.rQlen < 4) return;
sock.rQshift8(); // type
const length = sock.rQshift24();
if (sock.rQlen < length) return;
const data = sock.rQshiftBytes(length);
processMessage(data);
break;
}
});
```
--------------------------------
### Check Server Capabilities
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/rfb.md
Indicates which optional server capabilities are available. Updated after connection establishment. Checks for power control and audio streaming capabilities.
```javascript
if (rfb.capabilities.power) {
// Server supports power control
rfb.machineShutdown();
}
```
```javascript
if (rfb.capabilities.audio) {
// Server supports audio
rfb.enableAudio(2, RFB.audioCodecs.OpusWebM, 128);
}
```
--------------------------------
### RFB Constructor
Source: https://github.com/replit/novnc/blob/master/docs/API.md
The RFB() constructor creates a new RFB object and initiates a connection to a specified VNC server. It requires a target HTML element and a URL or data channel for the VNC server. Optional parameters can configure sharing, credentials, and WebSocket protocols.
```APIDOC
## RFB()
### Description
Initiates a new connection to a specified VNC server.
### Syntax
let rfb = new RFB( target, url [, options] );
### Parameters
#### `target`
- A block [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) that specifies where the `RFB` object should attach itself.
#### `urlOrDataChannel`
- A `DOMString` specifying the VNC server to connect to. This must be a valid WebSocket URL. This can also be a `WebSocket` or `RTCDataChannel`.
#### `options` (Optional)
- An `Object` specifying extra details about how the connection should be made.
Possible options:
`shared`
- A `boolean` indicating if the remote server should be shared or if any other connected clients should be disconnected. Enabled by default.
`credentials`
- An `Object` specifying the credentials to provide to the server when authenticating.
- `
```
--------------------------------
### Basic VNC Connection
Source: https://github.com/replit/novnc/blob/master/_autodocs/README.md
Establishes a basic WebSocket connection to a VNC server. Listen for connect and disconnect events.
```javascript
import RFB from './core/rfb.js';
const rfb = new RFB(
document.getElementById('vnc-screen'),
'ws://vnc-server.example.com:6080'
);
rfb.addEventListener('connect', () => {
console.log('Connected to remote desktop');
});
rfb.addEventListener('disconnect', (e) => {
if (!e.detail.clean) {
console.error('Disconnected unexpectedly');
}
});
```
--------------------------------
### Draw Rectangles with Different Colors
Source: https://github.com/replit/novnc/blob/master/_autodocs/types.md
Utilize the Color object to specify RGB values for drawing filled rectangles on the display. Each example shows how to set a different primary color (red, green, blue) for a rectangle.
```javascript
// Red color
display.fillRect(0, 0, 100, 100, {r: 255, g: 0, b: 0});
// Green color
display.fillRect(100, 0, 100, 100, {r: 0, g: 255, b: 0});
// Blue color
display.fillRect(200, 0, 100, 100, {r: 0, g: 0, b: 255});
```
--------------------------------
### Mapping Keyboard Codes to XT Scancodes
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/utilities.md
Shows how to map keyboard codes to XT scancodes using the XtScancode object. Import is required.
```javascript
import XtScancode from './core/input/xtscancodes.js';
XtScancode['KeyA']; // Scancode for 'A' key
XtScancode['ControlLeft']; // Scancode for Ctrl
```
--------------------------------
### Handle Capabilities Event
Source: https://github.com/replit/novnc/blob/master/_autodocs/types.md
Listens for the 'capabilities' event to receive updated capabilities, such as power and audio support. Use the 'e.detail.capabilities' object to check for specific features like 'power'.
```javascript
rfb.addEventListener('capabilities', (e) => {
const caps = e.detail.capabilities;
if (caps.power) {
// Show power control buttons
}
});
```
--------------------------------
### Encoding for Desktop Environments
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/decoders.md
Set quality and compression levels for GUI environments with mostly windows and text. Hextile or Tight encoding is recommended.
```javascript
// GUI with mostly windows and text
rfb.qualityLevel = 7; // Good quality
rfb.compressionLevel = 3; // Balanced compression
// Hextile or Tight encoding recommended
```
--------------------------------
### Viewport and Scaling
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/display.md
Explains how to manage the display viewport, including enabling clipping for scrollable areas, changing viewport size and position, and applying scaling.
```APIDOC
## Viewport and Scaling
### Description
Demonstrates how to control the viewport and scaling of the display.
### Usage
```javascript
// Enable viewport clipping (scrollable)
display.clipViewport = true;
display.viewportChangeSize(800, 600);
// Pan the viewport
display.viewportChangePos(50, 50);
// Enable scaling
display.scale = 0.75;
```
```
--------------------------------
### Basic RFB Connection
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/rfb.md
Establishes a basic connection to a VNC server via WebSocket. Listen for 'connect', 'credentialsrequired', and 'disconnect' events.
```javascript
import RFB from './core/rfb.js';
const rfb = new RFB(
document.getElementById('screen'),
'ws://vnc.example.com:6080'
);
rfb.addEventListener('connect', () => {
console.log('Connected to VNC server');
});
rfb.addEventListener('credentialsrequired', (e) => {
rfb.sendCredentials({ password: 'mypassword' });
});
rfb.addEventListener('disconnect', (e) => {
if (!e.detail.clean) {
console.error('Unexpected disconnect');
}
});
```
--------------------------------
### Lazy Load RFB Instance
Source: https://github.com/replit/novnc/blob/master/_autodocs/INTEGRATION_GUIDE.md
Load the RFB module dynamically when it's needed to improve initial load performance. Initialize the VNC connection on demand when a user action triggers it.
```javascript
// Load RFB only when needed
async function initializeVNC(container, url) {
const { default: RFB } = await import('./core/rfb.js');
return new RFB(container, url);
}
// Initialize on demand
document.getElementById('connect-btn').onclick = async () => {
const rfb = await initializeVNC(container, url);
// ...
};
```
--------------------------------
### RFB Constructor
Source: https://github.com/replit/novnc/blob/master/docs/API.md
Creates and returns a new RFB object, representing a single connection to a VNC server.
```APIDOC
## RFB()
### Description
Creates and returns a new `RFB` object.
### Method
Constructor
### Endpoint
N/A (JavaScript API)
### Parameters
None
```
--------------------------------
### Initialize RFB Connection
Source: https://github.com/replit/novnc/blob/master/docs/API.md
Instantiates a new RFB object to connect to a VNC server. The target HTMLElement is where the RFB object will attach itself. The URL specifies the VNC server, and optional parameters can configure sharing, credentials, and repeater IDs.
```javascript
let rfb = new RFB( target, url [, options] );
```
--------------------------------
### Extended Keyboard Pseudo-Encoding
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/decoders.md
Enables QEMU Extended Key Event support for better keyboard handling, especially on international keyboards.
```javascript
console.log(encodings.pseudoEncodingQEMUExtendedKeyEvent); // -258
```
--------------------------------
### enableAudio
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/rfb.md
Enables audio streaming from the remote server. Requires the Replit audio extension to be supported.
```APIDOC
## enableAudio(channels, codec, kbps)
### Description
Enables audio streaming from the remote server. Replit audio extension must be supported.
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **channels** (number) - Required - Number of audio channels (1 = mono, 2 = stereo)
- **codec** (number) - Required - Audio codec (RFB.audioCodecs.OpusWebM or RFB.audioCodecs.MP3)
- **kbps** (number) - Required - Bitrate in kilobits per second
### Request Example
```javascript
if (rfb.capabilities.audio) {
// Enable stereo Opus audio at 128 kbps
rfb.enableAudio(2, RFB.audioCodecs.OpusWebM, 128);
}
```
### Response
#### Success Response (200)
- **undefined** - This method does not return a value.
#### Response Example
None
```
--------------------------------
### Enable Auto-Resize to Window
Source: https://github.com/replit/novnc/blob/master/_autodocs/README.md
Set `resizeSession` to `true` to automatically resize the noVNC session to fit the browser window. A 'connect' event listener can log confirmation.
```javascript
rfb.resizeSession = true;
rfb.addEventListener('connect', () => {
console.log('Remote desktop will resize when window changes');
});
```
--------------------------------
### RFB Constructor: Specify Target
Source: https://github.com/replit/novnc/blob/master/_autodocs/errors.md
When initializing RFB, the target parameter must be a valid HTMLElement. Provide the DOM element where the VNC display will be rendered.
```javascript
// Wrong
const rfb = new RFB(null, url);
// Correct
const rfb = new RFB(document.getElementById('screen'), url);
```
--------------------------------
### open(url, protocols)
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/websock.md
Opens a WebSocket connection to the specified URL. It can optionally take an array of protocols.
```APIDOC
## open(url, protocols)
### Description
Opens a WebSocket connection to the specified URL.
### Parameters
#### Path Parameters
- **url** (string) - Required - WebSocket URL (ws:// or wss://)
- **protocols** (Array) - Optional - WebSocket subprotocols to negotiate
### Returns
undefined
### Throws
- **SyntaxError**: Invalid URL syntax
- **Error**: Connection error
### Example
```javascript
sock.open('ws://vnc.example.com:6080');
sock.open('wss://secure.example.com/vnc', ['proto1', 'proto2']);
```
```
--------------------------------
### Websock() Constructor
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/websock.md
Creates a new Websock instance for WebSocket/RTCDataChannel communication. It does not take any parameters.
```APIDOC
## Websock()
### Description
Creates a new Websock instance for WebSocket/RTCDataChannel communication.
### Parameters
None
### Returns
Websock instance
### Example
```javascript
import Websock from './core/websock.js';
const sock = new Websock();
sock.on('message', () => {
// Data available in receive queue
});
sock.open('ws://server.example.com:6080');
```
```
--------------------------------
### Monitor VNC Connection Analytics
Source: https://github.com/replit/novnc/blob/master/_autodocs/INTEGRATION_GUIDE.md
Implement this script to track connection times and send analytics data. It logs connection duration and monitors quality/compression levels periodically.
```javascript
// analytics.js
import RFB from './core/rfb.js';
const rfb = new RFB(container, serverUrl);
const metrics = {
connectionStart: Date.now(),
connectionTime: null,
bytesSent: 0,
bytesReceived: 0
};
rfb.addEventListener('connect', () => {
metrics.connectionTime = Date.now() - metrics.connectionStart;
console.log(`Connected in ${metrics.connectionTime}ms`);
// Send analytics
fetch('/api/analytics/vnc-connect', {
method: 'POST',
body: JSON.stringify({
connectionTime: metrics.connectionTime,
timestamp: new Date()
})
});
});
rfb.addEventListener('disconnect', () => {
console.log(`Session duration: ${Date.now() - metrics.connectionStart}ms`);
});
// Monitor quality during session
setInterval(() => {
console.log(`Quality: ${rfb.qualityLevel}, Compression: ${rfb.compressionLevel}`);
}, 30000);
```
--------------------------------
### capabilities
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/rfb.md
Indicates which optional server capabilities are available. Updated after connection establishment.
```APIDOC
### capabilities
Type: `Object` | Read-only
Indicates which optional server capabilities are available. Updated after connection establishment.
```javascript
if (rfb.capabilities.power) {
// Server supports power control
rfb.machineShutdown();
}
if (rfb.capabilities.audio) {
// Server supports audio
rfb.enableAudio(2, RFB.audioCodecs.OpusWebM, 128);
}
```
Available capabilities:
- `power`: boolean - Machine power control available
- `audio`: boolean - Audio streaming available
```
--------------------------------
### VNC Connection with Display Options
Source: https://github.com/replit/novnc/blob/master/_autodocs/README.md
Configures display options for the VNC session, including auto-scaling, resizing, quality, compression, and background color.
```javascript
const rfb = new RFB(target, url);
// Auto-scale to container
rfb.scaleViewport = true;
// Auto-resize remote when window changes
rfb.resizeSession = true;
// High quality (for good networks)
rfb.qualityLevel = 8;
rfb.compressionLevel = 2;
// Custom background
rfb.background = 'black';
```
--------------------------------
### Basic RFB Connection
Source: https://github.com/replit/novnc/blob/master/_autodocs/00-START-HERE.txt
Establishes a basic connection to a VNC server using the RFB class. Ensure the target element and WebSocket URL are correctly specified.
```javascript
import RFB from './core/rfb.js';
const rfb = new RFB(target, 'ws://vnc-server.example.com:6080');
rfb.addEventListener('connect', () => console.log('Connected'));
```
--------------------------------
### Handle WebSocket Open Event
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/websock.md
Log a message to the console when the WebSocket connection is successfully established.
```javascript
sock.on('open', () => {
console.log('Connected');
});
```
--------------------------------
### Listen for Credentials Required Event
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/rfb.md
Fires when the server requires authentication credentials that were not provided during initialization. Inspect the 'types' detail property to determine which credentials are needed.
```javascript
rfb.addEventListener('credentialsrequired', (e) => {
const types = e.detail.types; // Array of required credential types
if (types.includes('username')) {
// Request username and password
}
});
```
--------------------------------
### List Current noVNC Services
Source: https://github.com/replit/novnc/blob/master/README.md
Displays the currently configured noVNC services managed by Snap. This command is useful for checking existing service configurations before making changes.
```bash
sudo snap get novnc services
```
--------------------------------
### desktopname Event
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/rfb.md
Fired when the remote desktop name changes.
```APIDOC
## Event: desktopname
### Description
Fired when the remote desktop name changes.
### Event Detail
- **name** (string) - New remote desktop name
### Example
```javascript
rfb.addEventListener('desktopname', (e) => {
console.log('Desktop name:', e.detail.name);
});
```
```
--------------------------------
### Basic RFB Connection
Source: https://github.com/replit/novnc/blob/master/_autodocs/INDEX.md
Establishes a basic connection to a VNC server using the WebSocket protocol. Ensure the target element is correctly defined in your HTML.
```javascript
import RFB from './core/rfb.js';
const rfb = new RFB(target, 'ws://server:6080');
rfb.addEventListener('connect', () => console.log('Connected'));
```
--------------------------------
### Basic RFB Connection with Password
Source: https://github.com/replit/novnc/blob/master/_autodocs/configuration.md
Establish a basic RFB connection to a VNC server using WebSocket, providing only the password for authentication.
```javascript
const rfb = new RFB(
document.getElementById('screen'),
'ws://vnc.example.com:6080',
{
credentials: {
password: 'mypassword'
}
}
);
```
--------------------------------
### Instantiate Display Class
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/display.md
Create a new Display instance by providing the target canvas element. Ensure the target is a valid HTMLCanvasElement with a getContext method.
```javascript
import Display from './core/display.js';
const canvas = document.getElementById('vnc-canvas');
const display = new Display(canvas);
```
--------------------------------
### XVP (eXtendable VNC Protocol) Pseudo-Encoding
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/decoders.md
Enables power control capabilities like shutdown, reboot, and reset if `rfb.capabilities.power` is true.
```javascript
console.log(encodings.pseudoEncodingXvp); // -309
```
```javascript
if (rfb.capabilities.power) {
rfb.machineShutdown();
rfb.machineReboot();
rfb.machineReset();
}
```
--------------------------------
### Listen for Desktop Name Change Event
Source: https://github.com/replit/novnc/blob/master/_autodocs/api-reference/rfb.md
Fires when the remote desktop name changes. The new name is available in the event detail.
```javascript
rfb.addEventListener('desktopname', (e) => {
console.log('Desktop name:', e.detail.name);
});
```