Install react-vnc via npm
mainTo add react-vnc to your project, use the following command:
npm i react-vncrepository·main·Indexed 41 days ago
https://github.com/roerohan/react-vncA React component wrapper around the noVNC web client (version 3.2.0) that allows developers to embed a VNC stream into a web application via WebSockets. It provides the VncScreen component for rendering VNC sessions, supporting both WebSocket URLs and pre-authenticated WebSocket instances, along with an imperative API via VncScreenHandle for controlling connections and sending inputs.
To add react-vnc to your project, use the following command:
npm i react-vncThe primary way to display a VNC stream is by using the VncScreen component. You must provide either a url or a websocket prop.
Example usage with a WebSocket URL:
import React, { useRef } from 'react';
import { VncScreen } from 'react-vnc';
function App() {
const ref = useRef();
return (
<VncScreen
url='ws://your-vnc-url.com'
scaleViewport
background="#000000"
style={{
width: '75vw',
height: '75vh',
}}
ref={ref}
/>
);
}
export default App;If you need to perform a custom handshake, handle cookie-based authentication, or use connection pooling, you can pass a pre-authenticated WebSocket instance to the websocket prop instead of a url.
Example of manual authentication before passing the socket to VncScreen:
import React, { useEffect, useState } from 'react';
import { VncScreen } from 'react-vnc';
function App() {
const [websocket, setWebsocket] = useState<WebSocket | null>(null);
useEffect(() => {
// Create WebSocket and handle authentication
const ws = new WebSocket('ws://your-vnc-server.com');
ws.addEventListener('open', () => {
// Perform custom authentication or handshake
ws.send(JSON.stringify({ token: 'your-auth-token' }));
});
ws.addEventListener('message', (event) => {
const response = JSON.parse(event.data);
if (response.authenticated) {
// Once authenticated, pass the WebSocket to VncScreen
setWebsocket(ws);
}
});
return () => {
ws.close();
};
}, []);
if (!websocket) {
return <div>Authenticating...</div>;
}
return (
<VncScreen
websocket={websocket}
scaleViewport
style={{
width: '75vw',
height: '75vh',
}}
/>
);
}You can attach a ref to the VncScreen component to programmatically control the connection and interact with the VNC session. The VncScreenHandle provides the following methods and properties:
type VncScreenHandle = {
connect: () => void;
disconnect: () => void;
connected: boolean;
sendCredentials: (credentials: NoVncOptions["credentials"]) => void;
sendKey: (keysym: number, code: string, down?: boolean) => void;
sendCtrlAltDel: () => void;
focus: () => void;
blur: () => void;
machineShutdown: () => void;
machineReboot: () => void;
machineReset: () => void;
clipboardPaste: (text: string) => void;
rfb: RFB | null;
loading: boolean;
eventListeners: EventListeners;
};The VncScreen component accepts several props to configure the VNC session.
Required Props (Exactly one of these):
url: A ws:// or wss:// websocket URL.websocket: A pre-authenticated WebSocket instance.Optional Props:
style: CSS object for the component container.className: CSS class name.viewOnly: Boolean to disable user input.rfbOptions: Partial configuration for the underlying noVNC RFB instance.focusOnClick: Whether to focus the VNC session on click.clipViewport: Whether to clip the viewport.dragViewport: Whether to allow dragging the viewport.scaleViewport: Whether to scale the viewport to fit.resizeSession: Whether to resize the VNC session when the container changes.showDotCursor: Whether to show the dot cursor.background: Background color string.qualityLevel: Number for quality settings.compressionLevel: Number for compression settings.autoConnect: Whether to connect automatically.retryDuration: Duration to wait before retrying a connection.debug: Boolean for debug mode.Event Callbacks:
Callbacks can accept a single parameter rfb (the noVNC RFB object).
onConnect: Triggered when connection is established.onDisconnect: Triggered when connection is lost (includes retry logic by default).onCredentialsRequired: Triggered when authentication is needed.onSecurityFailure: Triggered on security errors.onClipboard: Triggered on clipboard events.onBell: Triggered on bell events.onDesktopName: Triggered when desktop name is received.onCapabilities: Triggered when capabilities are received.onClippingViewport: Triggered on clipping viewport events.type EventListeners = { [T in NoVncEventType]?: (event: NoVncEvents[T]) => void };
interface Props {
url?: string;
websocket?: WebSocket;
style?: object;
className?: string;
viewOnly?: boolean;
rfbOptions?: Partial<NoVncOptions>;
focusOnClick?: boolean;
clipViewport?: boolean;
dragViewport?: boolean;
scaleViewport?: boolean;
resizeSession?: boolean;
showDotCursor?: boolean;
background?: string;
qualityLevel?: number;
compressionLevel?: number;
autoConnect?: boolean;
retryDuration?: number;
debug?: boolean;
onConnect?: EventListeners['connect'];
onDisconnect?: EventListeners['disconnect'];
onCredentialsRequired?: EventListeners['credentialsrequired'];
onSecurityFailure?: EventListeners['securityfailure'];
onClipboard?: EventListeners['clipboard'];
onBell?: EventListeners['bell'];
onDesktopName?: EventListeners['desktopname'];
onCapabilities?: EventListeners['capabilities'];
onClippingViewport?: EventListeners['clippingviewport'];
}The VncScreen component exposes a VncScreenHandle via forwardRef. This allows you to programmatically control the VNC session (e.g., connecting, disconnecting, or sending keys) from a parent component.
connect(): Manually initiate a connection.disconnect(): Manually terminate the connection.sendCredentials(credentials): Sends authentication details (username, password, target).sendKey(keysym, code, down): Sends a keyboard event.sendCtrlAltDel(): Sends the Ctrl+Alt+Del sequence.focus(): Sets focus to the VNC session.blur(): Removes focus from the VNC session.machineShutdown(): Sends a shutdown request to the remote machine.machineReboot(): Sends a reboot request to the remote machine.machineReset(): Sends a reset request to the remote machine.clipboardPaste(text): Pastes the specified text into the remote clipboard.connected (boolean): Indicates if the session is currently connected.loading (boolean): Indicates if the component is in a loading state (e.g., during connection attempts).rfb (RFB | null): Access to the underlying noVNC RFB instance.eventListeners (EventListeners): The current registered event listeners.import { useRef } from 'react';
import VncScreen, { VncScreenHandle } from './VncScreen';
const Parent = () => {
const vncRef = useRef<VncScreenHandle>(null);
const handleReboot = () => {
vncRef.current?.machineReboot();
};
return (
<>
<button onClick={handleReboot}>Reboot Remote Machine</button>
<VncScreen ref={vncRef} url="ws://example.com/vnc" />
</>
);
};The VncScreen component is the primary interface for rendering a VNC stream in React. It accepts several props to control connection details, visual behavior, and event handling. You must provide either a url or a websocket to establish a connection.
url (string): The WebSocket URL for the VNC server.websocket (WebSocket): An existing WebSocket instance to use.autoConnect (boolean): If true (default), the component attempts to connect immediately on mount.retryDuration (number): The duration in milliseconds to wait before retrying a connection after an unexpected disconnect (default: 3000).rfbOptions (Partial<NoVncOptions>): Configuration options passed directly to the underlying noVNC RFB instance.viewOnly (boolean): If true, prevents user input from being sent to the server.focusOnClick (boolean): Automatically focuses the VNC session when the user clicks the screen.clipViewport (boolean): Clips the viewport to the container size.dragViewport (boolean): Allows dragging the viewport.scaleViewport (boolean): Scales the viewport to fit the container.resizeSession (boolean): Resizes the remote session when the container size changes.showDotCursor (boolean): Shows a dot cursor.background (string): The background color/style for the container.qualityLevel (number): VNC quality level (default: 6).compressionLevel (number): VNC compression level (default: 2).VncScreen provides several callbacks for VNC lifecycle events:
onConnect: Triggered when a connection is established.onDisconnect: Triggered when the connection is lost.onCredentialsRequired: Triggered when the server requests authentication. Use this to provide credentials via sendCredentials on the component ref.onSecurityFailure: Triggered on security-related errors.onClipboard: Triggered on clipboard events.onBell: Triggered when the remote bell is rung.onDesktopName: Triggered when the desktop name is received.onCapabilities: Triggered when capabilities are received.onClippingViewport: Triggered on clipping viewport events.<VncScreen
url="ws://example.com/vnc"
autoConnect={true}
onConnect={() => console.log('Connected!')}
onCredentialsRequired={(e) => handleAuth(e)}
/>To interact with the VncScreen component programmatically (e.g., to trigger specific VNC actions), you can use a React ref typed with VncScreenHandle. This handle provides access to the underlying component's imperative API.
import { useRef } from 'react';
import { VncScreen, type VncScreenHandle } from 'react-vnc';
const MyComponent = () => {
const vncRef = useRef<VncScreenHandle>(null);
const handleClick = () => {
// Use the handle to call methods on the VNC instance
vncRef.current?.someMethod();
};
return <VncScreen ref={vncRef} /* ...props */ />;
};The VncScreen component is the primary entry point for rendering a VNC session in a React application. It accepts configuration via VncScreenProps.
import { VncScreen } from 'react-vnc';The VncScreenProps type defines the configuration options available for the VncScreen component, such as WebSocket URLs, authentication details, and display settings.
import { VncScreen, type VncScreenProps } from 'react-vnc';
const props: VncScreenProps = {
// Configuration options defined by the library
};
const App = () => <VncScreen {...props} />;