What Web Can Do Today?

Can I rely on the Web Platform features to build my app?

An overview of the device integration HTML5 APIs

Serial Port

The Web Serial API allows Web applications to interact with the devices connected to the system via Serial Port. In order to authorize the application to get the access to the device, user needs to confirm the intent in the browser's UI that in turn may only be initiated with a gesture (for example, a button click, but not automatically by arbitrary JavaScript). The API exposes the connectivity via a pair of Streams – one for reading and one for writing into the serial port.

The specification, as of Spring 2020, is in design phase and early experimental implementations in Google Chrome only. Using it requires participation in Origin Trial program.

API glimpse

const port = await navigator.serial.requestPort()
Returns the Promise resolved with the port object representing the connection after user's consent.
port.open(options)
Returns the Promise resolved when the system establishes a connection through the serial port.
port.getInfo()
Returns a set of metadata about the connected device, including its serial number, name and manufacturer data.
port.readable
Returns a ReadableStream representing the data incoming via the serial port.
port.writable
Returns a WritableStream representing the data being sent from the system via the serial port.

Live Demo

Demo from Google Developers codelabs.

  • document.getElementById('connectButton').addEventListener('click', () => {
      if (navigator.serial) {
        connectSerial();
      } else {
        alert('Web Serial API not supported.');
      }
    });
    
    async function connectSerial() {
      const log = document.getElementById('target');
        
      try {
        const port = await navigator.serial.requestPort();
        await port.open({ baudRate: 9600 });
        
        const decoder = new TextDecoderStream();
        
        port.readable.pipeTo(decoder.writable);
    
        const inputStream = decoder.readable;
        const reader = inputStream.getReader();
        
        while (true) {
          const { value, done } = await reader.read();
          if (value) {
            log.textContent += value + '\n';
          }
          if (done) {
            console.log('[readLoop] DONE', done);
            reader.releaseLock();
            break;
          }
        }
      
      } catch (error) {
        log.innerHTML = error;
      }
    }
  • <button id="connectButton">Connect via Serial Port</button>
    
    <div id="target"></div>
    
    <p><small>Demo from <a href="https://codelabs.developers.google.com/codelabs/web-serial/" target="_blank" rel="noopener">Google Developers</a> codelabs.</small></p>

Resources

Get in touch