### Hyperbeam Hello World Example Source: https://github.com/hyperbeam A foundational example for getting started with Hyperbeam. This repository is ideal for new users to quickly set up and understand the basic Hyperbeam workflow. ```HTML 🌍 Getting started example for Hyperbeam ``` -------------------------------- ### Virtual Computer Session Response Source: https://docs.hyperbeam.com/home/getting-started Example JSON response received after successfully creating a virtual computer session. It contains essential identifiers and URLs for accessing and managing the session. ```json { "session_id": "52f968cb-6739-4197-83d7-2305fe5d6f54", "embed_url": "https://vwdrccwgpv181powg61ggyvy.hyperbeam.com/Uvloy2c5QZeD1yMF_l1vVA?token=c8iw3SmQglOU0ugfLr3dWY2LalSKI_WOGUldEt8knbw", "admin_token": "51JOZEEcMp4trCwbpTS3jjQc0lSmeAZpPfxioDqe73U" } ``` -------------------------------- ### Start Virtual Computer Session (CLI) Source: https://docs.hyperbeam.com/home/getting-started Initiates a new virtual computer session using a cURL command. Requires an API key for authorization. The response includes session details like session ID, embed URL, and admin token. ```bash curl -X POST -H 'Authorization: Bearer ' \ https://engine.hyperbeam.com/v0/vm ``` -------------------------------- ### Frontend to Control Virtual Computer Source: https://docs.hyperbeam.com/home/getting-started An HTML and JavaScript snippet demonstrating how to embed and control a Hyperbeam virtual computer. It fetches session details from the backend, initializes the Hyperbeam component, and allows programmatic navigation (e.g., opening YouTube) and listening to tab updates. ```html

Current website:

``` -------------------------------- ### Hyperbeam Virtual Machine API Endpoints Source: https://docs.hyperbeam.com/home/getting-started Documentation for key Hyperbeam API endpoints related to managing virtual computer sessions. This includes creating new sessions, listing active sessions, and ending existing sessions. ```APIDOC POST /v0/vm - Creates a new virtual computer session. - Headers: - Authorization: Bearer - Returns: - session_id: Unique identifier for the session. - embed_url: URL to embed the virtual computer in a web page. - admin_token: Token for administrative control of the session. GET /rest-api/dispatch/get-sessions - Lists all currently active virtual computer sessions. - Returns: An array of session objects, each containing session details. POST /rest-api/dispatch/ending-session - Ends a specific virtual computer session. - Requires session_id or other relevant identifiers to specify which session to end. - Returns: Confirmation of session termination. ``` -------------------------------- ### Node.js Backend to Start Virtual Computer Source: https://docs.hyperbeam.com/home/getting-started A Node.js Express server that acts as a backend. It makes a POST request to the Hyperbeam API to create a virtual computer session if one doesn't already exist, and returns the session details. ```javascript const express = require("express"); const axios = require("axios"); const app = express(); let computer; // Get a virtual computer object. If no object exists, create it. app.get("/computer", async (req, res) => { if (computer) { res.send(computer); return; } const resp = await axios.post( "https://engine.hyperbeam.com/v0/vm", {}, { headers: { Authorization: `Bearer ${process.env.HB_API_KEY}` }, } ); computer = resp.data; res.send(computer); }); app.listen(8080, () => console.log("Server start at http://localhost:8080")); ``` -------------------------------- ### Emulator Session Response Example Source: https://docs.hyperbeam.com/rest-api/dispatch/start-android-emulator-session An example of the JSON response received after successfully initiating an Android Emulator session. ```json { "session_id": "52f968cb-6739-4197-83d7-2305fe5d6f54", "embed_url": "https://vwdrccwgpv181powg61ggyvy.hyperbeam.com/Uvloy2c5QZeD1yMF_l1vVA?token=c8iw3SmQglOU0ugfLr3dWY2LalSKI_WOGUldEt8knbw", "admin_token": "51JOZEEcMp4trCwbpTS3jjQc0lSmeAZpPfxioDqe73U" } ``` -------------------------------- ### Hyperbeam Web SDK Example Source: https://docs.hyperbeam.com/client-sdk/javascript/examples An example demonstrating how to initialize the Hyperbeam Web SDK, interact with the tab API (create, duplicate, update, reload, go back/forward), and handle user interface elements like buttons and volume sliders. It also shows how to listen for tab update events. ```html
Volume:

User ID:

Current website:

``` ```javascript import Hyperbeam from "https://unpkg.com/@hyperbeam/web@latest/dist/index.js" // TODO: Set the embedURL variable const embedURL = "" const hb = await Hyperbeam(container, embedURL) userId.innerText = hb.userId hb.tabs.onUpdated.addListener((tabId, changeInfo) => { if (changeInfo.title) { currentSite.innerText = changeInfo.title } }) // Create a tab const tab = await hb.tabs.create({ active: true }) // Duplicate a tab const tab2 = await hb.tabs.duplicate(tab.id) // Set the URL of the active tab const updatedTab = await hb.tabs.update({url: "https://hyperbeam.dev/"}) // Button click handlers reload.addEventListener("click", () => { hb.tabs.reload() }) back.addEventListener("click", () => { hb.tabs.goBack() }) forward.addEventListener("click", () => { hb.tabs.goForward() }) youtube.addEventListener("click", () => { hb.tabs.update({ url: "https://youtube.com" }) }) range.addEventListener("change", (e) => { hb.volume = e.target.value / 100 }) ``` -------------------------------- ### Start a VM Instance with cURL Source: https://docs.hyperbeam.com/rest-api/dispatch/dispatch-overview Example using cURL to initiate a virtual machine instance. This request includes the necessary Authorization header with a bearer token. ```bash curl -X POST \ -H 'Authorization: Bearer BImPtQWrCnb7aceCdlGQ-qniBJFNH2-1tVv7OjoHuQA' \ https://engine.hyperbeam.com/v0/vm ``` -------------------------------- ### Hyperbeam Examples Source: https://github.com/hyperbeam A collection of examples designed for users who learn best by doing. This repository showcases various use cases and implementations of Hyperbeam. ```HTML 🛠️ For those that learn by example ``` -------------------------------- ### Hyperbeam sendEvent API and Examples Source: https://docs.hyperbeam.com/client-sdk/javascript/examples Documents the `hb.sendEvent` method for sending keyboard, mouse, and wheel events to the Hyperbeam browser. Includes examples for keydown, keyup, mousemove, mousedown, mouseup, and wheel events with their respective parameters. ```APIDOC hb.sendEvent(event: KeyEvent | MouseEvent | WheelEvent): void Sends a keyboard, mouse, or mouse wheel event to the Hyperbeam browser. ``` ```javascript const keyEvent = { type: "keydown", // type can be set to "keydown" and "keyup" // String denoting which key is pressed. // See https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values key: "A", ctrlKey: true, // Boolean indicating if the Ctrl key is pressed. Default is false. metaKey: false // Boolean indicating if the Meta key is pressed. Default is false. } const mouseEvent = { type: "mousedown" // type can be set to "mousemove", "mousedown", and "mouseup" x: 0.5, // The mouse's X position as a ratio, with a range of [0, 1] y: 0.5, // The mouse's Y position as a ratio, with a range of [0, 1] // Number that indicates which button was pressed on the mouse. Default is 0. // See https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button button: 2 } const wheelEvent = { type: "wheel", // Mouse wheel event, used for scrolling up or down deltaY: 20 // Positive value signifies scrolling down } hb.sendEvent(keyEvent) // Send CTRL+A keystroke hb.sendEvent(mouseEvent) // Right-click the center of the screen (0.5, 0.5) hb.sendEvent(wheelEvent) // Scroll down ``` -------------------------------- ### Start Cloud Computer with Webhook Auth Source: https://docs.hyperbeam.com/guides/authenticating-participants Example using curl to initiate a cloud computer session with webhook authentication enabled. Requires an API key for authorization. ```bash curl -X POST -H 'Authorization: Bearer ' \ https://engine.hyperbeam.com/v0/vm \ -d '{ "auth": { "type": "webhook", "value": { "url": "https://yourwebsite.com/webhook/hyperbeam/auth", "bearer": "" } } }' ``` -------------------------------- ### JavaScript Initialization Example Source: https://docs.hyperbeam.com/client-sdk/javascript/reference Demonstrates how to import the Hyperbeam SDK and initialize a HyperbeamClient instance within a JavaScript application. ```javascript import Hyperbeam from "@hyperbeam/web" // Assuming 'container' is a valid HTMLDivElement and 'embedURL' is a string // const container = document.getElementById('my-hyperbeam-container'); // const embedURL = "YOUR_EMBED_URL"; // const options = { timeout: 5000 }; const hb = await Hyperbeam(container, embedURL, options) ``` -------------------------------- ### Start Console Emulator API Source: https://docs.hyperbeam.com/rest-api/dispatch/start-console-emulator-session Initiates a Console Emulator session with specified parameters. Requires a console type and a URL to a ROM file. Supports authentication via a token object. Returns session details including an embed URL and admin token. ```APIDOC Start Console Emulator: Initiates a Console Emulator using Hyperbeam. Parameters: - type (string, required): The console type. Supported values: nes, snes, n64, ps1. - room_url (string, required): URL to a legal ROM file, which will be downloaded and loaded into the emulator. - auth (object, optional): The authentication system for the cloud computer. Defaults to {"type": "token"}. See the “cloud computer authentication” section for more info. Response: - session_id (string): The ID of the cloud computer session. - embed_url (string): A URL to load into the web client on your website. - admin_token (string): A token granting access to an exclusive subset of the client-side JavaScript SDK for setting permissions and programmatic navigation. Response Example: { "session_id": "52f968cb-6739-4197-83d7-2305fe5d6f54", "embed_url": "https://vwdrccwgpv181powg61ggyvy.hyperbeam.com/Uvloy2c5QZeD1yMF_l1vVA?token=c8iw3SmQglOU0ugfLr3dWY2LalSKI_WOGUldEt8knbw", "admin_token": "51JOZEEcMp4trCwbpTS3jjQc0lSmeAZpPfxioDqe73U" } ``` -------------------------------- ### Install Hyperbeam SDK via npm Source: https://docs.hyperbeam.com/client-sdk/javascript/overview Installs the Hyperbeam client-side JavaScript SDK using npm. This command adds the library as a dependency to your project, making it available for use in your Node.js or frontend projects. ```bash $ npm install @hyperbeam/web --save ``` -------------------------------- ### Hyperbeam Unity Integration Example Source: https://github.com/hyperbeam An example demonstrating the integration of Hyperbeam with the Unity game engine. This repository is for developers looking to use Hyperbeam in game development. ```ShaderLab ``` -------------------------------- ### Android Emulator Start API Source: https://docs.hyperbeam.com/rest-api/dispatch/start-android-emulator-session API endpoint for starting an Android Emulator session. Requires the Google Play Store application ID. Returns session details including an embed URL and admin token. ```APIDOC Start Android Emulator: Initiates an Android Emulator session. Parameters: body.app_id (string): The Google Playstore application ID. If not provided, the home screen will be loaded. Response: session_id (string): The ID of the cloud computer session. embed_url (string): A URL to load into the web client for embedding. admin_token (string): A token for exclusive access to client-side SDK features like permissions and programmatic navigation. Example Response: { "session_id": "52f968cb-6739-4197-83d7-2305fe5d6f54", "embed_url": "https://vwdrccwgpv181powg61ggyvy.hyperbeam.com/Uvloy2c5QZeD1yMF_l1vVA?token=c8iw3SmQglOU0ugfLr3dWY2LalSKI_WOGUldEt8knbw", "admin_token": "51JOZEEcMp4trCwbpTS3jjQc0lSmeAZpPfxioDqe73U" } ``` -------------------------------- ### Hyperbeam Babylon.js Integration Example Source: https://github.com/hyperbeam This repository provides an example of integrating Hyperbeam with Babylon.js, a powerful web 3D engine. It's intended for developers building 3D web experiences. ```HTML ``` -------------------------------- ### Hyperbeam A-Frame Integration Example Source: https://github.com/hyperbeam Demonstrates how to integrate Hyperbeam virtual computers within A-Frame applications. This repository is useful for developers building VR/AR experiences with Hyperbeam. ```JavaScript 🖼️ Hyperbeam virtual computers in A-Frame ``` -------------------------------- ### Hyperbeam API: Start Chromium Session Parameters Source: https://docs.hyperbeam.com/guides/resize-browser-window Configure the initial dimensions and maximum area for a new browser instance when starting a Chromium session. These parameters control the default size and resizing limits of the browser window. ```APIDOC POST /rest-api/dispatch/start-chromium-session Parameters: body.width (number, optional, default: 1280): The initial width of the browser window in pixels. body.height (number, optional, default: 720): The initial height of the browser window in pixels. body.max_area (number, optional, default: 1280*720): The maximum browser window area in pixels. This limits the browser window size when resizing. ``` -------------------------------- ### Custom Keyboard Event Handling with Hyperbeam Source: https://docs.hyperbeam.com/client-sdk/javascript/examples Provides an example of custom keyboard event handling by disabling default delegation and selectively forwarding events based on application logic. This is useful for managing key bindings and UI flows that might otherwise interfere with the Hyperbeam embed. ```javascript const hb = await Hyperbeam(container, embedURL, { delegateKeyboard: false, }); function onKeyEvent(e) { const { activeElement } = document; if ( // by default, events are ignored if an input element is in focus (!activeElement || (activeElement.nodeName !== "INPUT" && activeElement.nodeName !== "TEXTAREA" && !activeElement.isContentEditable)) && // your custom checks go here, for example (e.key === " " || e.key === "Enter") ) { hb.sendEvent({ type: e.type, key: e.key, ctrlKey: e.ctrlKey, metaKey: e.metaKey, }); } } window.addEventListener("keydown", onKeyEvent); window.addEventListener("keyup", onKeyEvent); ``` -------------------------------- ### Full Webhook Request Example Source: https://docs.hyperbeam.com/guides/authenticating-participants A comprehensive curl command demonstrating the actual request sent to the webhook endpoint, including necessary headers and the JSON body. ```bash curl -X POST -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -H 'HB-User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36' \ -H 'HB-Connection-IP: 203.0.113.195' \ https://yourwebsite.com/webhook/hyperbeam/auth \ -d '{"user_id": "7411d16b-9451-415e-bb65-7d5ff3202249", "userdata": {"my_data": "foo"}}' ``` -------------------------------- ### Handle Hyperbeam Initialization Errors Source: https://docs.hyperbeam.com/client-sdk/javascript/examples Illustrates how to catch and handle potential errors during the Hyperbeam client initialization. It specifically checks for `TimedOutError`, `TypeError` for invalid options, and `SessionTerminatedError`. ```javascript import Hyperbeam, { TimedOutError, SessionTerminatedError } from "Hyperbeam"; async function main() { let hb; try { hb = await Hyperbeam(container, embedURL, options); } catch (e) { switch (e.name) { case "TimedOutError": console.log("Request to load the embed URL timed out", e.message); break; case "TypeError": console.log( "Invalid options passed into the Hyperbeam constructor", e.message ); break; case "SessionTerminatedError": console.log("Session has already been terminated", e.message); break; } // Alternatively, if you can use instanceof // e.g. if (e instanceof TimedOutError) { ... } } } main(); ``` -------------------------------- ### Hyperbeam Session Configuration Parameters Source: https://docs.hyperbeam.com/rest-api/dispatch/start-chromium-session Defines the configurable parameters for setting up and managing Hyperbeam LLM sessions. This includes browser initialization, session timeouts, user interaction gestures, profile management, and extension installation. ```APIDOC SessionParameters: start_url: string (default: "about:blank") The initial URL to load in the browser. If unset and a profile is loaded, tabs from the profile are restored. kiosk: boolean (default: false) Enables kiosk mode, hiding the browser navigation UI. timeout: object Defines session termination timeouts and webhook notifications. - absolute: number Time in seconds since creation after which the session terminates. - inactive: number Time in seconds since the last user input after which the session terminates. - offline: number (default: 3600) Time in seconds with no users connected after which the session terminates. Resets when a user connects. - warning: number (default: 60) Time in seconds before a session is terminated due to another timeout. - webhook: object Configuration for timeout webhook events. - url: string The URL to send timeout webhook events to. - bearer: string The Bearer Token to send with the webhook. touch_gestures: object Enables touch gestures for touch screen devices. - swipe: boolean (default: false) Enables swipe gestures for browser history navigation. - pinch: boolean (default: false) Enables pinch gestures for zooming. Requires disabling viewport scaling in HTML with ``. tenant_id: string Custom ID for tracking usage on a per-tenant basis. control_disable_default: boolean (default: false) If true, users cannot control the browser by default and require manual admin grant. region: string (default: "NA") The server region: "NA" (North America), "EU" (Europe), "AS" (Asia). profile: boolean | string | object Used to save and load Chrome profiles (bookmarks, history, passwords, cookies). - true: Creates a new profile. - string: Loads an existing profile by its session ID. - object: - load: string ID of the session to load as a profile. - save: boolean | string (default: "false") If true, creates a new persisted profile. If a session ID is provided, overwrites the profile associated with that ID. adblock: boolean (default: false) Installs an adblock extension on the cloud browser. ublock: boolean (default: false) (deprecated) Deprecated. Use the `adblock` flag instead. draw: boolean (default: false) Installs a drawing and annotation extension on the cloud browser. extension: object Used to install custom Chrome extensions (Max Size 1MB). ``` -------------------------------- ### Manual Reconnection (JavaScript) Source: https://docs.hyperbeam.com/client-sdk/javascript/examples Provides a method to manually trigger a reconnection to the virtual browser. This can be useful for debugging connection issues. ```javascript manualReconnectBtn.addEventListener("click", () => { hb.reconnect(); }); ``` -------------------------------- ### Set User Permissions (JavaScript) Source: https://docs.hyperbeam.com/client-sdk/javascript/examples Sets specific permissions for a user identified by their ID. Requires an admin token to be set. Permissions include priority, idle timeout, and control disabling. ```javascript const targetUserId = "a_user_id"; const permissions = { priority: 2, // Higher value = higher priority idle_timeout: 3000, // Milliseconds until considered idle control_disabled: true, // Ignore all control input }; hb.setPermissions(targetUserId, permissions); ``` -------------------------------- ### Set Admin Token (JavaScript) Source: https://docs.hyperbeam.com/client-sdk/javascript/examples Sets the client's admin token, which is required for managing user permissions and programmatically controlling tabs. The token can be provided during initialization or set afterward. ```javascript // You can provide the admin token during initialization const hb = await Hyperbeam(container, embedURL, { adminToken: "admin_token_from_rest_api_response", }); // Or set it after initialization const hb = await Hyperbeam(container, embedURL); hb.adminToken = "admin_token_from_rest_api_response"; ``` -------------------------------- ### Initialize Hyperbeam Client with Options Source: https://docs.hyperbeam.com/client-sdk/javascript/examples Demonstrates how to create a new Hyperbeam client instance with various configuration options. It shows setting timeouts, admin tokens, volume, and various callback functions for handling frames, audio, cursor movements, disconnections, and connection state changes. ```javascript const embedURL = "https://abc.hyperbeam.com/foo?token=bar" const container = document.getElementById("container-id") const hb = await Hyperbeam(container, embedURL, { // Number of milliseconds until the request to the virtual browser times out. // If the request times out, the returned promise will be rejected. timeout: 5000, // default = 2000 // An admin token returned from the REST API that will grant this user // access to managing user permissions and programmatic navigation. adminToken: "admin_token_from_rest_api_response", // Starting volume of the virtual browser volume: 0.2, // default = 1.0 // Starting video pause state of the virtual browser videoPaused: false, // default = false // delegate global keyboard events to the embed delegateKeyboard: true, // default = true // Callback called with the virtual computer's video frame data // For Chromium-based browsers, its type is ImageBitmap // For other browsers, it's a HTMLVideoElement // Most frameworks like Three.js and Babylon.js can handle both types automatically frameCb: (frame) => {}, // Callback called with an MediaStreamTrack of the virtual computer's audio stream audioTrackCb: (track) => {}, // Data to be provided to your webhook endpoint if you're using webhook authentication webhookUserdata: {myAppData: {user: "your-app-user-id"}}, // Callback called when another user moves their mouse cursor on top of the virtual browser // Useful for implementing multiplayer cursors onCursor({ x, y, userId }) => {}, // Callback called when the user disconnects from the virtual browser // type is an enum with one of the following values: // "request" -> virtual browser was manually shut down // "inactive" -> inactive timeout was triggered // "absolute" -> absolute timeout was triggered // "kick" -> user was kicked from the session onDisconnect({ type }) => {}, // Callback called when a timeout either surpasses the warning threshold, // or has been reset and is no longer passed the warning threshold. // // type is an enum that refers to the timeout's type tied to the event // possible values are "inactive" and "absolute" // // deadline = null | { delay: number, closeDate: string } // If deadline is null, then the timeout was reset and is no longer // passed the warning threshold. If deadline is set, deadline.delay // is the number of milliseconds until the timeout is triggered, // and closeDate is an RFC3339 formatted string of when the timeout will occur onCloseWarning: ({ type, deadline }) => {}, // Callback called when the connection state of the video stream has changed // state = "connecting" | "playing" | "reconnecting" // // You can use this to show custom reconnecting UI, and detecting if a user // has a sub-optimal connection to the virtual browser onConnectionStateChange: ({ state }) => {} }) ``` -------------------------------- ### Get User ID (JavaScript) Source: https://docs.hyperbeam.com/client-sdk/javascript/examples Retrieves the unique client user ID for the current connection to the virtual browser. Each tab connected to the virtual browser will have a distinct user ID. ```javascript const hb = await Hyperbeam(container, embedURL); console.log(hb.userId); // A unique string identifying the user ``` -------------------------------- ### Hyperbeam SDK API Reference Source: https://docs.hyperbeam.com/client-sdk/javascript/examples Reference for core Hyperbeam SDK methods and properties, including volume control, user ID retrieval, stream pausing, admin token management, permission setting, reconnection, and resizing. ```APIDOC Hyperbeam(container: HTMLElement, embedURL: string, options?: HyperbeamOptions) Initializes the Hyperbeam instance. - container: The HTML element to embed the virtual browser into. - embedURL: The URL of the virtual browser. - options: Optional configuration object. HyperbeamOptions: adminToken?: string The admin token for managing permissions and control. HyperbeamInstance: volume: number Sets or gets the local volume for the virtual browser. Range: 0.0 to 1.0. Default: 1.0. userId: string Gets the client's unique user ID. videoPaused: boolean Sets or gets the video stream pause state. true to pause, false to resume. adminToken: string Sets the client's admin token. maxArea: number The maximum allowed area (width * height) in pixels for the virtual browser. width: number Gets the current width of the virtual browser. height: number Gets the current height of the virtual browser. setPermissions(userId: string, permissionData: PermissionData): Promise Sets permissions for a specific user. - userId: The ID of the user to set permissions for. - permissionData: An object containing permission settings. PermissionData: priority?: number Sets the user's priority. Higher values preempt lower priority users. Default: 0. idle_timeout?: number Time in milliseconds until the user is considered idle. Default: 0. control_disabled?: boolean If true, ignores all user control input. Default: control_disable_default. reconnect(): void Manually triggers a reconnection to the virtual browser. resize(width: number, height: number): Promise Resizes the virtual browser to the specified dimensions. - width: The new width in pixels. - height: The new height in pixels. Throws RangeError if width * height exceeds hb.maxArea. ``` -------------------------------- ### Upload Custom Chrome Extension via API Source: https://docs.hyperbeam.com/guides/install-chrome-extension Demonstrates how to upload a custom Chrome extension (zip or crx) to the Hyperbeam engine using a multipart form request. Includes examples for building the form data in JavaScript and making the API call with cURL. ```JavaScript function buildForm(extPath, vmConfig) { const formData = new FormData(); formData.append("ex", fs.createReadStream(extPath)); formData.append("body", JSON.stringify(vmConfig)); return formData; } const zipPath = path.resolve(__dirname, "./path/to/my/ext.zip"); const formData = buildForm(zipPath, { extension: { field: "ex" } }); const headers = formData.getHeaders(); headers["Authorization"] = `Bearer ${process.env.HB_API_KEY}`; const resp = axios.post('https://engine.hyperbeam.com/v0/vm', formData, {headers}); ``` ```Bash curl -X POST \ -H 'Authorization: Bearer ' \ -H 'Content-Type: multipart/form-data' \ https://engine.hyperbeam.com/v0/vm \ --form 'body={"extension":{"field":"ex"}}' \ --form 'ex=@/tmp/ext.zip;type=application/zip' # If using crx rather than zip, make sure to change the MIME-type to x-chrome-extension # --form 'ex=@/tmp/ext.crx;type=application/x-chrome-extension' ``` -------------------------------- ### Initialize Hyperbeam SDK Source: https://docs.hyperbeam.com/client-sdk/javascript/reference Initializes the Hyperbeam client by creating an instance of the HyperbeamClient. This is the primary entry point for interacting with the virtual browser and controlling its features. ```APIDOC Hyperbeam(container, embedURL, options?): Promise Initializes the Hyperbeam SDK and returns a HyperbeamClient instance. Parameters: container: HTMLDivElement | HTMLIFrameElement The DOM element where the virtual browser will be embedded. A `div` element is highly recommended. embedURL: string The URL used to embed the virtual browser, typically obtained from the Hyperbeam REST API. options?: HyperbeamOptions Object An optional object containing configuration settings for the virtual browser. HyperbeamOptions Object Properties: adminToken?: string An admin token from the REST API, granting permissions for managing user access and programmatic navigation. timeout?: number (default: 2000) The maximum time in milliseconds to wait for a virtual browser request. If this timeout is reached, the returned promise will be rejected. volume?: number (default: 1.0) The initial volume level for the virtual browser's audio output, ranging from 0.0 to 1.0. videoPaused?: boolean (default: false) The initial state of the virtual browser's video playback. If true, video will start paused. "hb.playoutDelay"?: boolean (default: false) Configures the playout delay. When true, input lag increases but video smoothness improves and frame drops are reduced. delegateKeyboard?: boolean (default: true) Determines whether global keyboard events should be delegated to the embedded virtual browser. webhookUserdata?: JSONValue Custom data to be sent to your webhook endpoint if webhook authentication is configured. frameCb?: (frame: ImageBitmap | HTMLVideoElement) => void A callback function that receives the virtual computer's video frame data. The type of the frame is `ImageBitmap` for Chromium-based browsers and `HTMLVideoElement` for others. audioTrackCb?: (track: MediaStreamTrack) => void A callback function that receives the virtual computer's audio stream as a `MediaStreamTrack`. onCursor?: (e: PeerMouseEvent) => void A callback function invoked when another user moves their mouse cursor within the virtual browser. Useful for implementing shared cursor experiences. onDisconnect?: (e: DisconnectEvent) => void A callback function triggered when a user disconnects from the virtual browser session. The event object `e` has a `type` property indicating the reason: "request" (manual shutdown), "inactive" (inactive timeout), "absolute" (absolute timeout), or "kick" (user removed). onCloseWarning?: (e: CloseWarningEvent) => void A callback function invoked when a timeout approaches its threshold or is reset. The event object `e` includes a `type` property for the timeout type ("inactive" or "absolute") and an optional `deadline` property detailing the remaining delay and the exact close date. onConnectionStateChange?: (e: ConnectionStateEvent) => void A callback function that reports changes in the video stream's connection state (e.g., "connecting", "playing", "reconnecting"). Useful for displaying custom UI for connection status or detecting suboptimal network conditions. Returns: Promise A promise that resolves with the HyperbeamClient instance upon successful initialization. ``` -------------------------------- ### cURL Example for User Deletion Source: https://docs.hyperbeam.com/rest-api/session/removing-users A command-line example using cURL to send a DELETE request to the user deletion API endpoint. ```bash curl -X DELETE -H "Authorization: Bearer " \ "/users/" ``` -------------------------------- ### Setup WebGL Template with Hyperbeam SDK (JavaScript) Source: https://docs.hyperbeam.com/client-sdk/unity/webgl/overview Integrates the Hyperbeam SDK into a Unity WebGL project by modifying the custom `index.html` template. This involves importing the Hyperbeam script and making the Unity instance accessible globally. Ensure this script is placed after the `createUnityInstance` call. ```JavaScript ``` ```JavaScript createUnityInstance(canvas, config).then((gameInstance) => { unityInstance = gameInstance }) ``` -------------------------------- ### Listen to Tab Events with Hyperbeam JavaScript Source: https://docs.hyperbeam.com/client-sdk/javascript/examples Demonstrates how to listen for tab creation events using Hyperbeam's JavaScript API, which mirrors Chrome's tab API. It shows how to add and remove listeners for tab events and create new tabs. ```javascript const hb = await Hyperbeam(container, embedURL); function onTabCreated(tab) { console.log(tab.id); } // Listen for when a new tab is created hb.tabs.onCreated.addListener(onTabCreated); // Create a new tab await hb.tabs.create({ active: true }); // Remove the event listener hb.tabs.onCreated.removeListener(onTabCreated); ``` -------------------------------- ### Get Single Session API Endpoint Source: https://docs.hyperbeam.com/rest-api/dispatch/get-session Fetches the details of a specific cloud computer session using its unique ID. Requires an Authorization header with a bearer token. The response includes the session ID, an embeddable URL, an admin token for programmatic control, and the session's termination date if applicable. ```APIDOC GET /v0/vm/{session_id} - Retrieves details for a specific cloud computer session. - Parameters: - session_id (path, string): The ID of the cloud computer session. - Headers: - Authorization (string): Bearer token for authentication. - Response Fields: - session_id (string): The ID of the cloud computer session. - embed_url (string): A URL you can load into the web client on your website. - admin_token (string): A token that grants access to the cloud computer API and an exclusive subset of the client-side web API. Needed for setting permissions and programmatic control. - termination_date (string or null): The termination time of the cloud computer session. Formatted according to RFC3339 (e.g. 2006-01-02T15:04:05Z07:00). null if the session hasn't terminated yet. - Request Example: ```bash curl -H 'Authorization: Bearer ' \ https://engine.hyperbeam.com/v0/vm/ ``` - Response Example: ```json { "session_id": "c5772689-2255-4e59-8cea-b846cda7ad4e", "embed_url": "https://96xljbfypmn3ibra366yqapci.hyperbeam.com/AAEjQFOIRnyeb81XbBsHMw?token=VTWsp1KGn4lLySRkUCmmAhsCcqJrPdhTXNS0Y-KPwHU", "admin_token": "DrXWd9QguPRSXwhQn4yJ66sExpoV0BZtAfZsseYECKo", "termination_date": null } ``` ``` -------------------------------- ### VM Usage Response Structure Source: https://docs.hyperbeam.com/rest-api/dispatch/get-usage Example JSON response structure for virtual machine usage data. ```json { "usage": [ { "date": "2024-02-01T00:00:00Z", "seconds": 2323 }, { "date": "2024-01-01T00:00:00Z", "seconds": 23232452 } ] } ``` -------------------------------- ### Optimize Server Location with Hyperbeam JavaScript Source: https://docs.hyperbeam.com/client-sdk/javascript/examples Explains how to optimize server location by first retrieving region information using `getRegionInfo()` client-side. The region code is then sent to a backend to be used when creating a session and generating an embed URL. ```javascript import Hyperbeam, { getRegionInfo } from "@hyperbeam/web"; async function createHyperbeam(container) { const regionInfo = await getRegionInfo(); // Pass region code to backend to be used during session creation const embedURL = await fetch(`/myapi?region=${regionInfo.region}`, { method: "POST", }); const hb = Hyperbeam(container, embedURL); return hb; } ``` -------------------------------- ### Browser Session Configuration Parameters Source: https://docs.hyperbeam.com/rest-api/dispatch/start-chromium-session Defines the configurable parameters for setting up a browser session. These options control aspects like display resolution, frame rate, cursor visibility, search engine, user agent, dark mode, quality settings, and locale. ```APIDOC APIDOC: BrowserSessionConfig: webgl: boolean (default: false) Enables WebGL. Some games and interactive activities require WebGL. width: number (default: 1280) Width of the browser in pixels. If set, height must be set as well. The max number of pixels (width * height) is capped at 1920*1080. height: number (default: 720) Height of the browser in pixels. If set, width must be set as well. The max number of pixels (width * height) is capped at 1920*1080. fps: number (default: 24) Integer frame rate of the browser. Must be in the range [24, 60]. hide_cursor: boolean (default: false) Hides the system cursor. Useful if you want to implement a multi-cursor user interface. search_engine: string | object (default: "duckduckgo") Sets the default search engine that Chromium uses. Possible values: "duckduckgo", "ecosia", "google", "startpage", "brave". Can also be a custom search engine object: { "name": "foo", "keyword": "f", "url": "https://foo.com/search?q={searchTerms}", "suggestions_url": "https://foo.com/suggest?q={searchTerms}" } user_agent: string Sets the user agent to a preset value. Currently only "chrome_android" is supported. dark: boolean (default: false) Enables dark mode. tag: string The tag property enforces uniqueness. If a session with tag "A" is already running and you attempt to make another session with tag "A", the endpoint will not create a new instance and will instead return the session_id and embed_url of the existing session. quality: object Used to toggle between "sharp", "smooth", and "blocky" quality modes. - mode: string (default: "smooth") Possible values are "sharp", "smooth", and "blocky". Enabling sharp mode triples the required bandwidth. locale: object Set the browser's locale and country. - language: string A comma-delimited list of languages, see the Accept-Language header. - country: string The ISO 3166 A-2 country code, e.g. US for the United States, CA for Canada. custom_extension_path: string Contains the path to your custom Chrome extension. ``` -------------------------------- ### Fetch VM Usage (cURL) Source: https://docs.hyperbeam.com/rest-api/dispatch/get-usage Example cURL command to fetch virtual machine usage data from the Hyperbeam API. ```bash curl -H "Authorization: Bearer " \ https://engine.hyperbeam.com/v0/vm/usage ```