UNPKG

22.5 kBMarkdownView Raw
1# Microblink JS
2
3*Microblink is deprecating this frontend solution to make way for a more efficient image acquisition component — [BlinkID ImageCapture In-browser SDK](https://github.com/BlinkID/blinkid-imagecapture-in-browser). You can still use this library but we will not provide technical support for it in case you encounter any issues and we won't be making any changes to it moving forward.*
4
5Javascript SDK for integrating with Microblink API
6
7[![npm version](https://badge.fury.io/js/microblink.svg)](https://badge.fury.io/js/microblink)
8
9[![NPM](https://nodei.co/npm/microblink.png?compact=true)](https://nodei.co/npm/microblink/)
10
11## Demo
12
13<!-- ./sample/demo-at-docs.md -->
14
15Demo app. implementation is available on [Codepen](https://codepen.io/microblink/pen/WaYReG/).
16
17More details about product with demo page are available [here](https://microblink.com/products/blinkid/web-api).
18
19## About
20
21This package includes library for image preparation and HTTP integration with Microblink API publicly hosted on https://api.microblink.com or for self hostend on-premise solution with Microblink API wrapped in Docker image, which is available on [Docker Hub](https://hub.docker.com/r/microblink/api/).
22
23Also, this package has an Microblink API UI web component available as custom HTML tag `<microblink-ui-web></microblink-ui-web>` which has native camera management for mobile and desktop devices with WebRTC support and file management solution.
24
25### Browser compatibility
26
27![Chrome](https://raw.githubusercontent.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.githubusercontent.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![IE](https://raw.githubusercontent.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![Safari](https://raw.githubusercontent.com/alrra/browser-logos/master/src/safari/safari_48x48.png)
28--- | --- | --- | --- |
29Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
30
31## How to use
32
33### Install package
34
35```
36npm install microblink
37```
38
39### Using CDN
40
41You can also link the scripts from unpkg: https://unpkg.com/microblink/dist/
42
43If you wish to use only SDK without UI component, use minified version [microblink.sdk.min.js](https://unpkg.com/microblink/dist/microblink.sdk.min.js)
44
45For the whole thing, we recommend using [es6 version](https://unpkg.com/microblink/dist/microblink.min.js) for better performance.
46If you really want es5, you can find minified version [here](https://unpkg.com/microblink/dist/microblink.es5.min.js).
47
48
49## Microblink API Proxy
50
51To avoid the leaking of your credentials (Microblink API Authorization header = API key + API secret) by your visitors in the frontend Javascript application, your frontend application in the production environment should has an access to the backend proxy application and backend proxy application should append the authorization credentials, and also in this proxy application you could execute your additional business logic.
52
53### Example implementation in Node.js Express application
54
55Minimum proxy implementation which ensure the security for your credentials are available here https://github.com/microblink/microblink-api-proxy-example this example can be easily hosted at Webtask.io service in few minutes. More details about this example are available in this [README.md](https://github.com/microblink/microblink-api-proxy-example/blob/master/README.md)
56
57## Using web component
58
59To skip developing your own front-end UI solution, we have included our web component in the package to provide you quick and easy integration, theme customization and labels translation.
60Under the hood we are using [WebComponents](https://www.webcomponents.org/) technology, custom elements and shadow DOM.
61Just insert our custom html element `<microblink-ui-web></microblink-ui-web>` into your page and the component will be rendered with initial setup.
62
63### Javascript events
64
65As we have developed our UI solution as a custom html element, we have also implemented it to dispatch additional HTML DOM events which can easily be accessed with javascript.
66Component fires two kind of events which are important for interacting with the rest of the page. Adding event listeners is the way to communicate with the component.
67
68**resultReady**
69This event is fired after successful image upload or scan and the results are available on the client side. By listening to this event you are able for example to fill out your web form with the extracted data.
70Plain javascript code example:
71
72```javascript
73document.querySelector('microblink-ui-web').addEventListener('resultReady', function(/*CustomEvent*/ event) {
74 var result = event.detail.result;
75 /* do something with the result */
76});
77```
78
79**error**
80This event is fired in case of any kind of error during component use. More information can be extracted from `ErrorEvent` argument such as error message. By listening to this event you can for example notify user of a failed scan, upload, connection error and so on.
81Plain javascript code example:
82
83```javascript
84document.querySelector('microblink-ui-web').addEventListener('error', function(/*ErrorEvent*/ event) {
85 var error = event.error, message = event.message;
86 /* do something with the error */
87});
88```
89
90### Setting component dimensions
91
92The component will initially stretch to the size of it's container. To control component's width and height, we recommend wrapping it inside a single `<div>` and setting css dimension properties on wrapper `<div>` element.
93For better UX, when viewing your page from a mobile browser, the component's height is set to 100% height of the viewport, but not more than a container's height. This gives you an option to control component's height inside viewport height range.
94
95### Attributes
96
97Currently the component supports four additional boolean attributes. These can be set like any other HTML attributes.
98
99**tabs** - this is for enabling results display inside component area after document scan or document file upload.
100Beside initial screen with action buttons, 2 more sections are rendered to which you can navigate via tab menu:
101table view of the results and preview of a JSON response from the server.
102
103**autoscroll** - this is a feature for mobile devices intended to improve UX. When scrolling through your page with this option enabled, the vertical positioning of the page will be set to the start of the component when distance of the component's top edge is near to the top edge of the viewport. This could help mobile users to have the whole component placed inside a viewport.
104
105**webcam** - this is for enabling or disabling the option to use web camera. To disable the use of webcam set the `webcam` attribute to "off".
106
107**upload** - this is for enabling or disabling the option to use upload image. To disable the use of upload image set the `upload` attribute to "off".
108
109**fullscreen** - this is for enabling or disabling the option to open web camera video stream fullscreen. To disable the use of fullscreen camera video stream set the `fullscreen` attribute to "off".
110
111### Localization
112
113If you wish to change textual contents inside component, we are offering you an easy way to do this without the need for you to do cumbersome additional javascript manipulation. Maybe you want your page in a different language or you just don't want our default English labels.
114As for the implementation details of this feature, we are using `<slot>` elements as placeholders in a shadow DOM structure. The slots will be generated automatically.
115
116`<microblink-ui-web>` has a method `setLocalization` which can receive JSON string or javascript object as parameter, containing translated or adjusted text for component's labels. This is the recommended way.
117Calling this method will reset current localization texts and place new ones.
118To clarify, we are providing an example with all currently customizable labels and their default values:
119
120```javascript
121document.querySelector('microblink-ui-web').setLocalization({
122 "buttons" : {
123 "browseDesktop": "Upload image",
124 "browseMobile": "Take or upload photo",
125 "cameraRemote": "Use mobile camera",
126 "cameraLocalDesktop": "Use web camera",
127 "cameraLocalMobile": "Use camera",
128 "dropFiles": "Drop files to upload",
129 "tryAgain": "TRY AGAIN",
130 "takePhoto": "Take a photo",
131 "copy": "Copy to clipboard",
132 "confirm": "USE PHOTO",
133 "retake": "RETAKE"
134 },
135 "labels" : {
136 "chooseInputMethod": "Choose input method",
137 "generatingExchangeLink": "Generating exchange link...",
138 "exchangeLinkTitle": "Exchange link is",
139 "openLinkAtSmartphone": "Please open exchange link at the smartphone with OR reader",
140 "remoteCameraIsPending": "Remote camera is pending...",
141 "remoteCameraIsOpen": "Remote camera is open...",
142 "imageIsUploading": "Image is uploading...",
143 "imageIsProcessing": "Image is processing...",
144 "videoTagUnsupported": "Your browser does not support video tag",
145 "uploading" : "Uploading",
146 "processing" : "Processing",
147 "analyzing" : "Analyzing",
148 "extracting" : "Extracting data",
149 "almostDone" : "Almost done",
150 "errorMsg": "We're sorry, but something went wrong. Please try again.",
151 "permissionMsg": "Enable camera please",
152 "notFoundErrorMsg": "No camera was found on your device",
153 "notAllowedErrorMsg": "You have denied camera access permission",
154 "scanningFinishedNoDataTitle": "Document not recognized",
155 "scanningFinishedNoDataMessage": "Please try again with a supported document or select a different recognizer",
156 "unsupportedFileType": "Unsupported file type",
157 "selectRecognizers": "Please select one or more recognizers to start scanning",
158 "noRecognizersSelected": "No recognizers selected",
159 "webRtcUnsupported": "WebRTC not supported by your browser"
160 },
161 "tabs" : {
162 "back": "Back",
163 "results": "Results",
164 "json": "JSON"
165 }
166});
167```
168
169To retain compatibility, we are supporting old, now discouraged way of interpolating json directly into html:
170
171You can provide JSON content via `<template class="localization">` element and place the template as a child of `<microblink-ui-web>`. The template text content should be an URL to external JSON file, or you can insert JSON directly as a template content in which case you should append "json" class to `<template>`.
172Here is an example with all currently customizable labels:
173
174```json
175<microblink-ui-web>
176 <template class="localization json">
177 {
178 "buttons" : {
179 "browseDesktop": "Upload image",
180 "browseMobile": "Take or upload photo",
181 "cameraRemote": "Use mobile camera",
182 "cameraLocalDesktop": "Use web camera",
183 "cameraLocalMobile": "Use camera",
184 "dropFiles": "Drop files to upload",
185 "tryAgain": "TRY AGAIN",
186 "takePhoto": "Take a photo",
187 "copy": "Copy to clipboard",
188 "confirm": "USE PHOTO",
189 "retake": "RETAKE"
190 },
191 "labels" : {
192 "chooseInputMethod": "Choose input method",
193 "generatingExchangeLink": "Generating exchange link...",
194 "exchangeLinkTitle": "Exchange link is",
195 "openLinkAtSmartphone": "Please open exchange link at the smartphone with OR reader",
196 "remoteCameraIsPending": "Remote camera is pending...",
197 "remoteCameraIsOpen": "Remote camera is open...",
198 "imageIsUploading": "Image is uploading...",
199 "imageIsProcessing": "Image is processing...",
200 "videoTagUnsupported": "Your browser does not support video tag",
201 "uploading" : "Uploading",
202 "processing" : "Processing",
203 "analyzing" : "Analyzing",
204 "extracting" : "Extracting data",
205 "almostDone" : "Almost done",
206 "errorMsg": "We're sorry, but something went wrong. Please try again.",
207 "permissionMsg": "Enable camera please",
208 "notFoundErrorMsg": "No camera was found on your device",
209 "notAllowedErrorMsg": "You have denied camera access permission",
210 "scanningFinishedNoDataTitle": "Document not recognized",
211 "scanningFinishedNoDataMessage": "Please try again with a supported document or select a different recognizer",
212 "unsupportedFileType": "Unsupported file type",
213 "selectRecognizers": "Please select one or more recognizers to start scanning",
214 "noRecognizersSelected": "No recognizers selected",
215 "webRtcUnsupported": "WebRTC not supported by your browser"
216 },
217 "tabs" : {
218 "back": "Back",
219 "results": "Results",
220 "json": "JSON"
221 }
222 }
223 </template>
224</microblink-ui-web>
225```
226
227You can use this example as a template and just change JSON values for your purposes.
228
229### Theme customization
230
231To avoid leaking css styles inside of a component or outside of it, we are using a shadow DOM for scoping purposes.
232This way the component's css is isolated from the rest of the page and there are no unintentional overrides.
233However, you probably wish to adjust component style so it can better fit with the rest of your page design.
234With this in mind, we provide style hooks in the form of CSS custom properties, also knows as CSS variables. CSS custom properties' values set on the component element have higher priority than those defaults set inside of the shadow DOM (`:host` selector) and for this reason they are able to pierce the barrier of the shadow DOM from the outside.
235We have defined dozens of custom properties so you have plenty of options when creating your own theme for the component. For more advanced styling options, such as creating your own layout, inserting icons at certain places, more labels and so on, you will have to directly manipulate HTML and CSS inside of the component's shadow DOM structure.
236Below is the list of all currently available style hooks with their explanations:
237
238
239| Property | Description |
240| :-------------------------------| :----------|
241| -\-mb-hem | This is basically CSS rem unit for the component. Default value is set to page's 1rem. If you wish to scale up or down text size of the component, use this property. Default: `1rem` |
242| -\-mb-widget-font-family | Use to define component's font family. Default: `Helvetica, Tahoma, Verdana, Arial, sans-serif` |
243| -\-mb-widget-border-width | Border width of the entire component. Default: `0` |
244| -\-mb-widget-border-color | Border color of the component. Default: `black` |
245| -\-mb-widget-background-color | Background color of the component. Default: `white` |
246| -\-mb-default-font-color | Font color of the choose input label and results display. Default: `black` |
247| -\-mb-alt-font-color | Font color of the initial display labels. Default: `#575757` |
248| -\-mb-btn-font-color | Buttons' font color. Default: `white` |
249| -\-mb-btn-background-color | Background color of buttons. Default: `#48b2e8` |
250| -\-mb-btn-background-color-hover | Background color of hovered buttons. Default: `#26a4e4` |
251| -\-mb-btn-alt-font-color | Font color of the webcam retake button. Default: `black` |
252| -\-mb-btn-alt-background-color | Background color of the webcam retake button. Default: `white` |
253| -\-mb-btn-border-radius | Set the buttons' border radius. Default: `0` |
254| -\-mb-btn-intro-stroke-color | Stroke color of choose input screen icons. Default: `black` |
255| -\-mb-btn-intro-stroke-color-hover | Stroke color of choose input screen icons on hover. Default: `white` |
256| -\-mb-btn-intro-circle-color | Background color of choose input screen icons. Default: `#f2f2f2` |
257| -\-mb-btn-intro-circle-color-hover | Background color of choose input screen icons on hover. Default: `#48b2e8` |
258| -\-mb-btn-container-border-color | Border color of footer on webcam image confirmation screen. Default: `lightgrey` |
259| -\-mb-spinner-border-width | Border width of the mobile camera status spinner. Default: `6px` |
260| -\-mb-capture-icons-color | Icon color of the flip image and close buttons. Default: `white` |
261| -\-mb-dropzone-hover-color | Background color of drag and drop area when hovered with some dragged document. Default: `rgba(72, 178, 232, 0.2)` |
262| -\-mb-dropzone-circle-color | Background color of drag and drop circle indicator. Default: `#48b2e8` |
263| -\-mb-dropzone-icon-color | Color of drag and drop indicator icon. Default: `black` |
264| -\-mb-loader-font-color | Font color of the loader dialog during file upload and processing. Default: `black` |
265| -\-mb-loader-background-color | Background color of the loader dialog. Default: `#48b2e8` |
266| -\-mb-card-layout-border-color | Border color of the card overlay. Default: `black` |
267| -\-mb-dialog-title-color | Font color of the permission and error dialogs title. Default: `black` |
268| -\-mb-dialog-message-color | Font color of the permission and error dialogs message. Default: `#575757` |
269| -\-mb-photo-icon-primary | Background color of webcam photo button and counter. Default: `white` |
270| -\-mb-photo-icon-accent | Accent color of webcam photo button and counter text. Default: `#48b2e8` |
271
272There are additional properties to style component if you are using 'tabs' option to display results inside a component.
273They are listed below:
274
275| Property | Description |
276| :----------------------------------- | :----------|
277| -\-mb-tabs-background-color | Background color of tabs. Default: `black` |
278| -\-mb-tabs-font-color | Font color of tabs. Default: `white` |
279| -\-mb-tabs-border-width | Bottom border width for underlined text inside tabs. Default: `4px` |
280| -\-mb-tabs-hover-color | Font color of hovered tab. Default: `#26a4e4` |
281| -\-mb-tabs-active-color | Font color of active tab, the one whose corresponding container is displayed. Default: `#48b2e8` |
282| -\-mb-json-color-key | Inside JSON view, font color of the keys. Default value: `black` |
283| -\-mb-json-color-string | Inside JSON view, font color of string values. Default value: `#48b2e8` |
284| -\-mb-json-color-boolean | Inside JSON view, font color of boolean values. Default value: `#26a4e4` |
285| -\-mb-json-color-number | Inside JSON view, font color of number values. Default value: `black` |
286| -\-mb-json-color-null | Inside JSON view, font color of the null values. Default value: `#26a4e4` |
287| -\-mb-results-border-color | Border color of results table. Default: `#dee2e6` |
288| -\-mb-results-image-border-radius | Border radius of results table extracted images. Default: `6px` |
289| -\-mb-results-image-background-color | Background color of results table extracted images when results are masked. Default: `#f2f2f2` |
290
291### Feature: desktop-to-mobile
292
293With this feature component is able to starts at the browser on the desktop computer and use remote camera on the smartphone to capture document, call API and returns results to the desktop where component was initially started.
294
295All data by default is exchanged over Firebase project through Firestore collection, this can be replaced by modifying the component and Microblink SDK internaly.
296
297#### Source
298
299Microblink Scan Web is a standalone Angular application available as GIT submodule at [scan](https://github.com/microblink/microblink-scan-web) directory.
300
301#### How it works
302
3031. component is loaded at the browser on desktop
3042. user requests feature by click to the button `Use mobile camera`
3053. component at the desktop generate exchange link with QR code and secret key for AES encryption
3064. user at smartphone should open generated exchange link (link contains scan identificator and AES secret key for encryption), recommended way is to scan QR code with QR reader integrated in native camera app on the iOS and Android or with custom QR reader
3075. at mobile user takes document with native camera
3086. component loaded at smartphone calls Microblink API, encrypt result and store it to the exchanged object at `Firebase.Firestore`
3097. component loaded at desktop is subscribed for the changes, reads encrypted results stored in `Firebase.Firestore`, decrypts it and display it to the user
310
311#### Firebase project setup
312
313Look at the [sample/index.html](./sample/index.html) and replace Firebase app configuration with your project's credentials. To exchange data through database which you are the owner.
314
315## SDK Setup
316
317SDK methods will allow you to manipulate with request according to your needs.
318
319Use this method if you are using country specific recognizers.
320Multiple recognizers are allowed here.
321```javascript
322Microblink.SDK.SetRecognizers(['MRTD']);
323```
324
325This method allows you to set the endpoint of the API service.
326If you are using Self-hosted API, set this to the address where your service is available.
327If you wish to test just the API functionality you can do that by using our demo service, which is available at https://demoapi.microblink.com.
328```javascript
329Microblink.SDK.SetEndpoint('http://localhost:8081');
330```
331
332This methods allows you to use our improved recognizers, or to test how our Cloud API works.
333Set request parameters for desired recognizer.
334This method will override Microblink.SDK.SetRecognizers() method.
335This way, you can use only one recognizer per request.
336Available recognizers are (BLINK_ID, ID_BARCODE, MRTD, PASSPORT, VISA and MRZ_ID).
337```javascript
338Microblink.SDK.SetupRecognizerRequest('MRTD');
339```
340
341Disable persisting uploaded data (this option is ignored if Authorization header is set).
342```javascript
343Microblink.SDK.SetIsDataPersistingEnabled(false);
344```
345Setup export images.
346```javascript
347Microblink.SDK.SetExportImages(true);
348```
349Set Authorization header (Bearer + ' ' + apiKey + apiSecret) - generate one in Microblink dashboard at https://microblink.com/customer/api.
350If endpoint is not equal to the default value `https://api.microblink.com` then `Authorization` header is ignored (self-hosted Microblink API by default has disabled authorization with Microblink API key/secret).
351```javascript
352Microblink.SDK.SetAuthorization('Bearer OTgzMGE95GU0YTA1NGQ1OTk5OTVhZjk3OTJiNjM0YzE6NWMyMzhiNzktYmE5My00MTMzLWFiNTHUMWRhYTk4NWI5Mzcz');
353```
354Set up UserID if needed.
355```javascript
356Microblink.SDK.SetUserId('test-user-id@microblink.com');
357```
358
359Default listeners (API's callbacks) are defined inside of the microblink-js UI component, but it is possible to configure global listeners to implement custom success/error handlers.
360```javascript
361Microblink.SDK.RegisterListener({
362 onScanSuccess: (data) => {
363 console.log('Data from Microblink API is', data);
364 },
365 onScanError: (error) => {
366 console.error('Error from Microblink API is', error);
367
368 // Display generic alert
369 if (error.summary) {
370 alert(error.summary);
371 }
372 }
373});
374```
375
376## Development
377
378`npm install`
379
380### Realtime watch & build
381
382`npm start`
383
384### Build release
385
386`npm build` and fetch files from `dist` directory
387
388