API Reference

This page provides a complete reference for all public APIs in the Anyline Web SDK.

init() Function

The main entry point for initializing the Web SDK.

Signature

function init(params: AnylineJSParams): AnylineJS

Parameters

license (required)

Type: string

Your Anyline license key as a base64-encoded string.

license: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...'

element (required)

Type: HTMLElement

The DOM container element where the scanner will be mounted.

element: document.getElementById('scanner-root')

preset (optional)

Type: PresetName

Pre-configured settings for common scanning use cases.

Available Presets
Category Preset Description

Barcode

qr

QR code scanning only

all_barcode_formats

All supported 1D and 2D barcode formats

barcode_pdf417

PDF417 barcode scanning

barcode_pdf417_parsed

PDF417 with AAMVA parsing (US driver’s licenses)

ID Scanning

universalid_mrz

Machine Readable Zone (passports, ID cards)

universalid_dl_at_de

Austrian and German driving licenses

universalid_dl_at_de_strict

AT/DE driving licenses with strict validation

universalid_es_it_pt

Spanish, Italian, and Portuguese driving licenses

License Plates

lpt

General license plate recognition

lpt_eu

European license plates

lpt_us

United States license plates

lpt_canada

Canadian license plates

Tire & Automotive

vin

Vehicle Identification Number (fast mode)

vin_with_user_guidance

VIN with real-time user guidance feedback

tin

Tire Identification Number

tin_dot

Tire DOT number

tire_size

Tire size information

tire_id

Complete tire identification

Containers

container

Horizontal shipping container codes

containerVertical

Vertical shipping container codes

Meters

meter

Analog and digital meter reading

dialmeter

Dial meter reading

verbund

Verbund utility meter

OCR

ocr

General optical character recognition

legacy_barcode

Legacy barcode engine (compatibility mode)

preset: 'all_barcode_formats'

config (optional)

Type: PluginConfig

Manual plugin configuration. When used with a preset, this configuration is merged with the preset’s configuration, allowing you to override or extend specific settings while keeping the rest of the preset intact. See Customizing Presets for details.

// Example: Using preset 'all_barcode_formats' but limiting the formats
preset: 'all_barcode_formats',
config: {
  barcodeConfig: {
    barcodeFormats: ['QR_CODE', 'DATA_MATRIX'],  // Overrides preset formats
    multiBarcode: true                            // Adds to preset config
  },
  cancelOnResult: true
}
When no preset is specified, this parameter must provide the complete plugin configuration.

See Plugin Configuration JSON Schema for complete schema.

viewConfig (optional)

Type: ViewConfig

UI/UX configuration for the scanner appearance. When used with a preset, this configuration is merged with the preset’s view configuration, allowing you to customize specific visual aspects while keeping the rest of the preset’s UI intact.

// Example: Using preset 'all_barcode_formats' but customizing the overlay color
preset: 'all_barcode_formats',
viewConfig: {
  outerColor: '000000',  // Overrides preset overlay color
  outerAlpha: 0.5,       // Overrides preset overlay opacity
  cutouts: [{
    cutoutConfig: {
      width: 720,           // Overrides preset cutout width
      maxWidthPercent: '80%',
      alignment: 'center'
    }
  }]
}
When no preset is specified, this parameter must provide the complete view configuration including cutout definitions.

See ViewConfig Reference for complete reference.

loadingScreen (optional)

Type: string

Can be used to customize the loading screen that shows before the camera feed becomes available.

loadingScreen: '<div class="loading-spinner">Preparing camera…</div>'

coverVideo (optional)

Type: boolean

Default: true

Controls whether the camera video should cover the container element. Turning this off can be useful when you need the letterboxed preview for custom layouts.

coverVideo: false

useFullUrlBundleId (optional)

Type: boolean

Switches on stricter bundle-id validation against the full URL path (domain + path). By default, only the domain part is checked.

useFullUrlBundleId: true

mirrorOnDesktop (optional)

Type: boolean

Default: true

Controls whether the desktop camera feed is mirrored. Disable when using a rear-facing webcam.

mirrorOnDesktop: false

correlationId (optional)

Type: string

A unique key in UUIDv4 format that can be optionally passed as an additional parameter. This ID can be assigned to a scan and all subsequent scans of a workflow or business process, whether from a single Anyline scanning capability or a series of scans from various Anyline scanning capabilities.

correlationId: '6f8664dc-3ff6-4f5b-9dc0-3f778a2f0f0f'

enableCaching (optional)

Type: boolean

Default: true

Controls the internal caching of SDK assets.

enableCaching: false

anylinePath (optional)

Type: string

Default: CDN path

Location of the Anyline asset files. For better performance, copy the anylinejs folder to your public directory and provide the path.

anylinePath: '/anylinejs'
// or
anylinePath: 'https://your-cdn.com/anylinejs'

See Optimizing performance for optimization strategies.

hapticFeedback (optional)

Type: boolean

Default: false

Enables audio and vibration feedback on successful scan.

Platform Support:

  • Audio feedback: Works on all platforms (Android, iOS, desktop browsers)

  • Vibration feedback: Android only (requires browser support for Vibration API)

hapticFeedback: true
On iOS, audio is played using the Web Audio API. On Android, audio is played via HTML Audio element and vibration is triggered using navigator.vibrate().

flashOnResult (optional)

Type: boolean

Default: false

Enables a visual flash animation (screen blink effect) when a result is detected.

Platform Support: Works on all platforms (Android, iOS, desktop browsers)

flashOnResult: true
This is a visual-only effect that displays a white overlay flash on the screen. It does not control the device’s camera flash.

preload (optional)

Type: boolean

Default: false

Enables asset preloading. When true, assets are loaded in advance using the preload() method. When used correctly, this parameter can significantly improve loading time. See Performance Optimization for more details.

preload: true

preloadCallback (optional)

Type: () ⇒ void

Callback function called when preloading is complete. Only used when preload: true.

preloadCallback: () => {
  console.log('Assets loaded, ready to scan');
  showStartButton();
}

mediaConstraints (optional)

Type: MediaStreamConstraints

Custom camera constraints for resolution, facing mode, etc. See the MDN MediaStreamConstraints documentation for available options.

mediaConstraints: {
  video: {
    width: { ideal: 1920 },
    height: { ideal: 1080 },
    facingMode: 'environment'
  }
}

retryCameraAccess (optional)

Type: boolean

Automatically retry camera access with fallback constraints when the initial attempt fails.

retryCameraAccess: true

estimateMainCamera (optional)

Type: boolean

Default: true

Attempts to automatically select the main/back camera on devices with multiple cameras.

estimateMainCamera: true

throttleImagePass (optional)

Type: number

Delay in milliseconds between frame processing. Useful for reducing CPU usage on low-end devices.

throttleImagePass: 100  // Process max 10 frames per second

initialFlashOn (optional)

Type: boolean

Default: false

Automatically enables camera flash on scanning start (Chrome for Android, Safari 18.4+).

initialFlashOn: true

slowMessageTimeout (optional)

Type: number

Default: 14000 (14 seconds)

Timeout in milliseconds before warning about slow initialization.

slowMessageTimeout: 30000  // 30 seconds

scaleDown (optional)

Type: boolean

Default: false

Scales down the processed image for potential performance boost in certain use cases (e.g., barcode scanning).

scaleDown: true

lockPortraitOrientation (optional)

Type: LockPortraitOrientation

Locks screen orientation to portrait mode. Requires fullscreen mode. Chrome Android only.

lockPortraitOrientation: {
  element: document.getElementById('fullscreen-container'),
  lock: true
}

landscapeOrientation (optional)

Type: LandscapeOrientation

Locks screen orientation to landscape mode. Requires fullscreen mode. Chrome Android only.

landscapeOrientation: {
  element: document.getElementById('fullscreen-container'),
  lock: true
}

debugAnyline (optional)

Type: boolean | 'screen'

Default: false

Enables debug logging. Use true for console logging or 'screen' for on-screen debug overlay.

debugAnyline: true

Returns

Returns an AnylineJS instance with methods and properties for controlling the scanner.

Example

import { init } from '@anyline/anyline-js';

const anyline = init({
  license: 'YOUR_LICENSE_KEY',
  element: document.getElementById('scanner-root'),
  preset: 'all_barcode_formats',
  hapticFeedback: true,
  flashOnResult: true
});

AnylineJS Class

The main SDK instance returned by init().

Methods

startScanning(): Promise<HTMLVideoElement | undefined>

Starts the scanning process by activating the camera and initializing the scan engine.

Returns: Promise<HTMLVideoElement | undefined> - Resolves with the video element when called from INITIALIZED state, or undefined when called from STOPPED or PAUSED states (internally calls resumeScanning())

Example:

try {
  const video = await anyline.startScanning();
  console.log('Scanning started', video);
} catch (error) {
  if (error instanceof AnylineError) {
    console.error(error.toString());
  } else {
    console.error('Unexpected error:', error);
  }
}
The promise rejects with a DisposedError when the instance has been disposed, AnylineError for licensing or configuration issues, and other Error instances (for example, camera permission errors) surfaced from the underlying browser APIs.

stopScanning(): void

Stops the current scanning session.

Example:

anyline.stopScanning();
console.log('Scanning stopped');
Use stopScanning() when the scanning session is complete. For temporary pauses, use pauseScanning() instead.

pauseScanning(): void

Pauses scanning while keeping the camera active. No frames are processed while paused.

Example:

anyline.pauseScanning();
console.log('Scanning paused');
Subsequent calls to pauseScanning() are ignored if already paused.

resumeScanning(): Promise<void>

Resumes scanning after pauseScanning() or stopScanning().

Returns: Promise<void> - Resolves when scanning resumes

Example:

await anyline.resumeScanning();
console.log('Scanning resumed');
Subsequent calls to resumeScanning() are ignored if already scanning.

dispose(): void

Completely unmounts the SDK from the DOM, terminates the worker, and cleans up all resources. Must call init() again to reinitialize.

Example:

anyline.dispose();
console.log('SDK disposed');
Always call dispose() when done with the SDK to prevent memory leaks.

getState(): State

Returns the current state of the SDK.

Returns: State - One of INITIALIZED, SCANNING, PAUSED, STOPPED, DISPOSED

Example:

import { State } from '@anyline/anyline-js';

const currentState = anyline.getState();

if (currentState === State.SCANNING) {
  console.log('Currently scanning');
}

See State Management for detailed state management guide.

setFocusDistance(distance?: number): void

Manually adjusts the camera focus distance on supported devices (Chrome Android).

Parameters: distance - Normalized focus distance value (0.0 to 1.0), where 0.0 represents infinity focus (farthest) and 1.0 represents the closest focus distance (macro). Omit or pass undefined to reset to the device default.

// Manually tweak focus when the device and browser support it
anyline.setFocusDistance(0.2);

getFrame(): ImageObject | undefined

Manually retrieves the current camera frame including full frame and cutout region.

Returns: ImageObject | undefined - Object containing fullImage and optional cutoutImage, or undefined if no frame available

interface ImageObject {
  fullImage: ImageData;
  cutoutImage?: ImageData;
}

Example:

const frame = anyline.getFrame();

if (frame) {
  console.log('Frame dimensions:', frame.fullImage.width, frame.fullImage.height);

  // Convert to canvas
  const canvas = document.createElement('canvas');
  canvas.width = frame.fullImage.width;
  canvas.height = frame.fullImage.height;
  const ctx = canvas.getContext('2d');
  ctx?.putImageData(frame.fullImage, 0, 0);

  // Get data URL
  const dataUrl = canvas.toDataURL();
}

preload(): void

Preloads SDK assets before starting scanning. Only works when initialized with preload: true.

Throws: Error - If preload was not set to true during initialization

Example:

const anyline = init({
  license: 'LICENSE',
  element: root,
  preset: 'all_barcode_formats',
  preload: true,
  preloadCallback: () => {
    console.log('Ready to scan instantly');
  }
});

// Preload assets early
anyline.preload();

// Later, start scanning with minimal delay
await anyline.startScanning();

See Preload Assets example for complete example.

Properties

camera: CameraAPI

Provides access to camera control methods.

Type: CameraAPI

Available methods:

  • mirrorStream(state: boolean) - Mirrors the camera stream

  • setCamera(deviceId: string) - Switches to specific camera

  • reappend() - Reappends camera stream (fixes issues after sleep)

  • refocus() - Manually triggers camera refocus (Android Chrome only)

  • activateFlash(state: boolean) - Controls camera flash (Chrome for Android, Safari 18.4+)

Example:

// Mirror camera for front-facing camera
anyline.camera.mirrorStream(true);

// Enable flash
await anyline.camera.activateFlash(true);

See Camera API for detailed documentation.

isLoaded: boolean

Indicates whether the SDK assets have finished loading.

Type: boolean

Example:

console.log('SDK loaded:', anyline.isLoaded);

Callbacks

onResult(result: AnylineJSResult): void

Called when a scan completes successfully with a result.

Parameters:

interface AnylineJSResult {
  result: any;                      // Plugin-specific result data
  fullImage: ImageData | undefined; // Full camera frame as ImageData (may be undefined)
  scanTime: number;                 // Scan duration in milliseconds
}

Example:

anyline.onResult = ({ result, fullImage, scanTime }) => {
  console.log('Scanned:', result);
  console.log('Scan time:', scanTime, 'ms');

  // Convert ImageData to data URL
  if (fullImage) {
    const canvas = document.createElement('canvas');
    canvas.width = fullImage.width;
    canvas.height = fullImage.height;
    const ctx = canvas.getContext('2d');
    ctx?.putImageData(fullImage, 0, 0);
    const imageUrl = canvas.toDataURL();
  }
};
Result structure varies by plugin type. See Plugin Result JSON Schema for details.

onError(error: LegacyErrorObject): void

Deprecated since version 31.0.0

Legacy error callback. Use try-catch with async/await instead for proper error handling.

Migration:

// ❌ Old (deprecated)
anyline.onError = (error) => {
  console.error(error.code, error.message);
};

// ✅ New (recommended)
try {
  await anyline.startScanning();
} catch (error) {
  console.error(error);
}

onLoad(video: HTMLVideoElement): void

Deprecated since version 31.0.0

Legacy callback called when scanning starts. Use the Promise returned by startScanning() instead.

Migration:

// ❌ Old (deprecated)
anyline.onLoad = (video) => {
  console.log('Loaded:', video);
};

// ✅ New (recommended)
const video = await anyline.startScanning();
console.log('Loaded:', video);

State Enum

Represents the SDK lifecycle state.

enum State {
  INITIALIZED = 'initialized',
  SCANNING = 'scanning',
  PAUSED = 'paused',
  STOPPED = 'stopped',
  DISPOSED = 'disposed'
}

States

INITIALIZED

SDK is initialized but not yet scanning. Camera is inactive.

SCANNING

SDK is actively processing frames and detecting objects.

PAUSED

Scanning is temporarily paused. Camera remains active.

STOPPED

Scanning session has ended. Camera may be inactive. Call resumeScanning() to start processing again.

DISPOSED

SDK has been completely unmounted and cleaned up. Must call init() again.

See State Management for state transitions and management patterns.


Complete Example

import { init, State, AnylineError } from '@anyline/anyline-js';

// Initialize SDK
const anyline = init({
  license: 'YOUR_LICENSE_KEY',
  element: document.getElementById('scanner-root'),
  preset: 'all_barcode_formats',
  hapticFeedback: true,
  debugAnyline: true
});

// Set up result callback
anyline.onResult = ({ result, fullImage, scanTime }) => {
  console.log('Scanned:', result);
  console.log('Time:', scanTime, 'ms');

  if (fullImage) {
    console.log('Image dimensions:', fullImage.width, 'x', fullImage.height);
  }

  // Stop scanning after result
  anyline.stopScanning();
};

// Start scanning with error handling
try {
  const video = await anyline.startScanning();
  console.log('Scanning started:', anyline.getState());
} catch (error) {
  if (error instanceof AnylineError) {
    console.error(error.toString());
  } else {
    console.error('Unexpected error:', error);
  }
}

// Pause scanning when page hidden
document.addEventListener('visibilitychange', () => {
  if (document.hidden && anyline.getState() === State.SCANNING) {
    anyline.pauseScanning();
  } else if (!document.hidden && anyline.getState() === State.PAUSED) {
    anyline.resumeScanning();
  }
});

// Clean up when done
window.addEventListener('beforeunload', () => {
  anyline.dispose();
});

See Also