JavaScript MRZ Scanner UI Components - SDK Features
The MRZ (Machine Readable Zone) Scanner is able to scan and decode the MRZ data on an ID card or passport.
Integrating the MRZ Scanner UI
Configuration
ScanbotSDK MRZ Scanner takes an instance of MrzScannerConfiguration
as its argument.
This is your main object for configuration options, styling and receiving the results.
MrzScannerConfiguration
inherits the base properties:
containerId
– Theid
of the containing HTML element where the MRZ Scanner will be initialized. RequiredvideoConstraints
– The desired video resolution. Optional, defaults to1920x1080
mirrored
- Whether the screen should be mirrored. Useful when using a user-facing camera.false
by defaultpreferredCamera
- Camera label or camera device id. If not available, a default camera is used as fallbackonError
– Callback when something went wrong. Optional
Additionally, ScanbotSDK MRZ Scanner has the following configurable options:
onMrzDetected
– Your callback for receiving detection results. RequiredaccumulatedFrameVerificationConfiguration
– Configures when a scan result should be considered verified, i.e. when it'sverificationSuccessful
property will betrue
. Optional. Should be set to an object with the following properties:maximumNumberOfAccumulatedFrames: number
– Maximum number of accumulated frames to inspect to verify a scan result.3
by default.minimumNumberOfRequiredFramesWithEqualRecognitionResult: number
– Minimum number of accumulated frames that have an equal result.2
by default.
The result of onMrzDetected
is a MrzResult
object that contains the following properties:
documentNumber?: MrzField;
issuingAuthority?: MrzField;
departmentOfIssuance?: MrzField;
givenNames?: MrzField;
surname?: MrzField;
nationality?: MrzField;
birthDate?: MrzField;
gender?: MrzField;
expiryDate?: MrzField;
personalNumber?: MrzField;
travelDocType?: MrzField;
travelDocTypeVariant?: MrzField;
optional1?: MrzField;
optional2?: MrzField;
discreetIssuingStateOrOrganization?: MrzField;
kindOfDocumentField?: MrzField;
documentType?: MrzField;
format?: MrzField;
pinCode?: MrzField;
languageCode?: MrzField;
versionNumber?: MrzField;
checkDigits?: MrzCheckDigits;
verificationSuccessful?: boolean;
MrzCheckDigits
contains values of various check digit types as follows:
general?: MrzField;
documentNumber?: MrzField;
birthDate?: MrzField;
expiryDate?: MrzField;
personalNumber?: MrzField;
MrzField
contains the following fields:
name?: string;
value?: string;
confidence?: number;
validated?: MRZFieldValidationStatus;
MRZFieldValidationStatus
is a custom type:
type MRZFieldValidationStatus =
'Success'
| 'Failure'
| 'NotValidated';
Styling
ScanbotSDK MRZ Scanner has the following style options and their default values:
style?: {
window: {
aspectRatio: 4,
widthProportion: 0.8,
borderColor: "white",
left: "50%",
top: "50%",
transform: "translate(-50%, -50%)"
},
text: {
color: string = "white";
size: string = "0.9em";
weight: number = 300;
},
hint: "Please align the code in the frame above to scan it"
backgroundColor: string = "rgba(0, 0, 0, 0.7)";
}
window
element is used to configure the viewfinder. It uses the WindowStyleConfiguration
interface that has the following attributes:
width?: string;
height?: string;
aspectRatio?: number;
widthProportion?: number;
borderColor?: string;
left?: string;
top?: string;
transform?: string;
width
and height
elements can be used for configuring the size of the viewfinder in pixels. However, aspectRatio
and widthProportion
elements can be used for configuring the size of the viewfinder in a more responsive way.
aspectRatio
specifies the aspect ratio as width/height.
widthProportion
specifies the proportional length of the viewfinder. (1 means full length of the visible area of the scanner.)
To change a specific style, simply assign it another value, e.g:
configuration.style = { window: { borderColor: "pink" } };
Default style configuration:
const WindowStyle: WindowStyleConfiguration = {
aspectRatio: 4,
widthProportion: 0.8,
borderColor: "white",
left: "50%",
top: "50%",
transform: "translate(-50%, -50%)"
}
const TextStyle: TextStyleConfiguration = {
color: "white",
size: "0.9em",
weight: 300,
}
const MrzScannerStyle: ViewFinderConfiguration = {
window: WindowStyle,
text: TextStyle,
backgroundColor: "rgba(0, 0, 0, 0.7)",
hint: "Please hold the device over the MRZ code to start scanning"
}
Opening the Scanner
To open the MRZ Scanner, simply call the relevant SDK function with the configuration object:
const config = {
containerId: MRZ_SCANNER_CONTAINER,
onMrzDetected: onMrzDetected,
onError: onError
};
const scanner = await scanbotSDK.createMrzScanner(configuration);
You should store the MRZ Scanner object in a globally accessible location, as additional MRZ Scanner actions are functions of that object.
API
To handle MRZ results (avoid duplicate scans etc), ScanbotSDK offers the following convenient methods to pause and resume detection while you are processing the data on your side:
resumeDetection(): void;
pauseDetection(): void;
isDetectionPaused(): boolean;
Switching between the front and rear camera
swapCameraFacing(force?: boolean): void;
swapCameraFacing(true)
indicates that only the swapped camera (e.g. front camera) is acceptable; if the swapped camera is not available, or the user declines the permission to use that camera, the media request will fail.
Firefox on Android: Due to current Firefox browser limitations, we highly recommend checking the running browser and disabling this feature for Firebox browsers.
Switching to a specific available camera
fetchAvailableCameras(): Promise<CameraInfo[]>;
switchCamera(deviceId: string, mirrored?: boolean): void;
getActiveCameraInfo(): CameraInfo | undefined;
interface CameraInfo {
deviceId: string;
label: string;
facingMode?: CameraFacingMode;
supportsTorchControl?: boolean;
}
type CameraFacingMode = 'front' | 'back' | 'unknown';
You can search for available cameras on the running browser by using fetchAvailableCameras
method of a scanner.
You can retrieve the label, device id and the camera facing mode information of the active camera of a scanner by using getActiveCameraInfo
method.
And, you can switch to another available camera by utilizing its device id, by using switchCamera
method.
const cameras = await scanner.fetchAvailableCameras()
if (cameras) {
const currentCameraInfo = scanner.getActiveCameraInfo();
if (currentCameraInfo) {
const cameraIndex = cameras.findIndex((cameraInfo) => { return cameraInfo.deviceId == currentCameraInfo.deviceId });
const newCameraIndex = (cameraIndex + 1) % (cameras.length);
scanner.switchCamera(cameras[newCameraIndex].deviceId);
}
}
Controlling the torch (flashlight)
On some mobile devices, the browser can control the torch (flashlight).
Check scanner.getActiveCameraInfo().supportsTorchControl
to see if the browser can control the torch for the currently active camera.
If true, you can control the torch by using the setTorchState
method of the scanner
.
setTorchState(state: boolean): Promise<void>;
On Android devices, only Chrome supports torch control. Starting with iOS 17.4, all supported browsers on iOS offer torch control functionality.
Disposal
As with the Document Scanner, the MRZ Scanner should also be properly disposed of when you have detected and processed the relevant MRZ:
await mrzScanner.dispose();
Detection on the Image
async createSimpleMRZRecognizer(): Promise<SimpleMrzRecognizer>
Example usage:
...
reader.readAsDataURL(file);
reader.onload = async (e) => {
const recognizer = await scanbotSDK.createSimpleMRZRecognizer();
const result = await recognizer.recognizeURL(reader.result);
this.onMrzDetected(result);
await recognizer.release();
};
Want to scan longer than one minute?
Generate your free "no-strings-attached" Trial License and properly test the Scanbot SDK.
Get your free Trial LicenseWhat do you think of this documentation?
What can we do to improve it? Please be as detailed as you like.