What is TWTwainJS for web?

TWTwain for web is a Terminalworks scanning product which allows you that visitors of your web site can perform scanning operations from their locally installed scaner devices.

How it works?

It has two parts:

  1. TWTwainJS - written in plain Javascript
  2. TWTwainClient - .NET windows application

On your website, where you want to provide web scanning functionality, you will use TWTwainJS product to create an instance of TWTwainJS. TWTwainJS instance opens a socket connection with the TWTwainClient. If you are web developer, you are primarly interested in TWTwainJS. TWTwainJS.zip is available at https://www.terminalworks.com/twtwainjs/downloads

TWTwainClient is the doing communication with web visitor's local scanners. Requirements to make it work:

  • web visitor must have already installed TWTwainClient on its computer
  • TWTwainClient is a .NET windows application and it will work only on Windows OS (Windows Vista and newer)
  • web visitor's scan devices must have TWAIN driver

TWTwainClient installer is available at https://www.terminalworks.com/twtwainjs/downloads

How to start using it?

If you are web developer: Extract TWTwainJS.zip. Let presume that you have index.html and index.js and you plan to support modern browsers which supports ES2015. in index.html

<script type="module" src="index.js"></script>

in index.js

import TWTwainJS, { ScanSettings, TWDeviceName, TWEvent, TWJSConnectionStatus } from "./src/TWTwainJS.js";
import { CapEnum, CapName } from "./src/TWTwainJSCapabilities.js";

const twTwainJS = new TWTwainJS("yourTwainInstance", "demoCompany", "demoKey");
twTwainJS
  .connectToClient(50000, 50020) // the client opens the first free port from 50000 up
  .then((result) => {
    if (result.status === TWJSConnectionStatus.CONNECTED) {
      let scanSettings = new ScanSettings(TWDeviceName.DEFAULT);
      scanSettings.showUI = true;
      scanSettings.closeUIAfterAcquire = true;
      scanSettings.scanFormatType = CapEnum.TWScanFormatType.JPEG;
      twTwainJS
        .scan(scanSettings)
        .then((result) => {
          console.log("scan finished with result:", result);
        })
        .catch((error) => {
          console.log("scan finished with error:", error);
        });
    }
  })
  .catch((error) => {
    console.log("connectToClient error:", error);
  });

window.addEventListener(TWEvent.PAGE_SCANNED, function (e) {
  console.log(e.detail.scanResult);
  console.log("Current page", e.detail.scanResult.images.length);
});

This simple example will try to open socket connection with the TWTwainClient. Once opened, it will scan on the local default device in the jpeg format. Scanner's settings dialog will be shown. On every page scanned, TWEvent.PAGE_SCANNED is triggered with the scanned image in its detail. For more advanced use (like settings TWAIN capabilites, saving in different formats like PDF or TIFF, downloading scanned results...) please visit https://www.terminalworks.com/twtwainjs/documentation/js-examples

If you are web visitor of the site where TWTwainJS is implemented:

  1. Install TWTwainClient on your Windows OS machine.
  2. Visit the web page where TWTwainJS is implemented.
  3. If the browser asks whether the site may access other apps and services on this device, choose Allow.

The browser asks for permission to reach TWTwainClient

TWTwainJS talks to TWTwainClient through a WebSocket to ws://127.0.0.1 on the visitor's computer. Chrome treats this as Local Network Access: a site on the internet needs the visitor's permission before it can reach apps on their device. Edge, which is based on Chromium, held the connection back the same way in our test (Edge 153).

What the visitor sees, measured with Chrome 154:

  • When connectToClient() reaches the port TWTwainClient listens on, Chrome asks: "<your site> wants to: Access other apps and services on this device", with Allow and Block. Ports with nothing listening on them fail at once and raise no question.
  • The answer is remembered for the site and can be changed later in the site settings (the icon left of the address), under Apps on device.
  • While the question is open, connectToClient() waits on that port, without a timeout. Tell the visitor what to do (see getLoopbackPermission() below); cancelConnect() stops the wait.
  • Closing the question with X is not an answer. The connection fails, the next port where something listens asks again, and after three closed questions Chrome blocks the site on its own for a while.

Which pages are affected:

Page served from What happens
a public address over HTTPS the question above, once per site
a public address over plain HTTP blocked without a question; serve the page over HTTPS
a private (intranet) address no question, connects as before (Chrome may extend the check to these later)
an iframe of another site blocked without a question unless the iframe has allow="loopback-network", see below

Telling a blocked page from a missing client. To the page, a connection the browser blocked looks exactly like a client that is not running. When connectToClient() finds no client, its promise is rejected with the error message, and TWEvent.TW_ERROR carries detail.errorCode:

  • TWErrorCode.LOOPBACK_PERMISSION_DENIED: the browser reports that the page may not reach apps on this device. The visitor chose Block, closed the question three times, or the page is in an iframe without the allow attribute. The message says what to allow.
  • TWErrorCode.CLIENT_NOT_FOUND: no client in the port range: not installed, not running, or listening outside the range. The message is the same as before ("No valid socket was found..."). A page over plain HTTP and a question closed with X end here too, because the browser does not report them; after a closed question detail.loopbackPermission is "prompt".

autoReconnect reports the same two codes when it gives up.

twTwainJS.getLoopbackPermission() returns the browser's answer so far, without asking anything: "granted", "prompt" (the visitor will be asked), "denied", or undefined when the browser has no such permission (Firefox, Safari, older Chrome) or the page is not served over HTTPS. Pages from a private address report "prompt" although they are not asked.

twTwainJS.getLoopbackPermission().then((permission) => {
  if (permission === "prompt") showHint("Your browser will ask to access apps on this device. Please choose Allow.");
});

window.addEventListener(TWEvent.TW_ERROR, (e) => {
  if (e.detail.errorCode === TWErrorCode.LOOPBACK_PERMISSION_DENIED) showError(e.detail.error);
  else if (e.detail.errorCode === TWErrorCode.CLIENT_NOT_FOUND) showError("Please install or start TWTwainClient.");
});

Iframes. A page shown in an iframe of another site may only ask when the iframe passes the permission on:

<iframe src="https://scan.example.com/" allow="loopback-network"></iframe>

The question then names the top-level site, and the answer belongs to it. Older Chrome versions used the name local-network-access; to cover them too, write allow="loopback-network; local-network-access". local-network-access also covers devices on the local network, which TWTwainJS does not need.

Managed browsers. Administrators can allow the site without the question with the Chrome policy LocalNetworkAccessAllowedForUrls, a list of URL patterns such as https://scan.example.com or [*.]example.com. On Windows these are string values 1, 2, ... under HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\LocalNetworkAccessAllowedForUrls (Edge: ...\Policies\Microsoft\Edge\...). Chrome and Edge 146 and newer also have LoopbackNetworkAllowedForUrls, which allows only connections to the visitor's own computer, exactly what TWTwainJS needs. Check the result in chrome://policy.

Licensing

To avoid watermark on your scanned pages, you need valid license key which you will retrieve on the purchase of the product. You set a license key on the TWTwainJS side.

const twTwainJS = new TWTwainJS("yourTwainJSInstanceName", "company", "licenseKey");

License is based on the allowed domain names which are set by a license owner while purchasing. So, if your website is on the domain www.yourdomain.com and you set that as allowed domain, license will work only if is run on www.yourdomain.com website. You have free 1 year upgrade and support.

Where can I see a demo to test how it really works?

Fully functional demo with watermark is available at https://www.terminalworks.com/twtwainjs/demo Also, source code of that demo is available in the TWTwainJS.zip file.

Where can I see some examples about implementing TWTwainJS?

Examples are available at this URL: https://www.terminalworks.com/twtwainjs/documentation/js-examples

Where can I see in the details about TWTwainJS?

Detailed reference is available at https://www.terminalworks.com/twtwainjs/documentation/js-reference

Where can I use TWTwainJS?

It is written in plain JS so it can be used in static sites, PHP, Django, ASP.NET Core... It is web technology agnostic. In TWTwainJS.zip is provided ES6 Javascript version which will work in modern browsers, and ES5 version for older browsers.

TWTwainJS uses window, CustomEvent and WebSocket object so:

  • it can't be used directly in the main process of the electron app, but it can be used in the renderer process
  • it can't be used in Node applications