### listen() - Enable Data Reception
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
The listen() method starts reading incoming data from the printer, such as status updates or acknowledgments.
```APIDOC
## listen()
### Description
Starts reading incoming data from the printer. Received data is emitted through the 'data' event.
### Response
- **data** (Uint8Array) - Emitted via the 'data' event containing bytes received from the printer.
```
--------------------------------
### Enable Data Reception with listen()
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
Starts reading incoming data from the printer, which is emitted via the 'data' event. Useful for monitoring printer status or acknowledgments.
```javascript
const receiptPrinter = new WebSerialReceiptPrinter({ baudRate: 9600 });
receiptPrinter.addEventListener('connected', async () => {
// Start listening for printer responses
await receiptPrinter.listen();
console.log('Listening for printer data');
});
receiptPrinter.addEventListener('data', (value) => {
// value is a Uint8Array of received bytes
console.log('Received from printer:', value);
// Parse status bytes (example for ESC/POS status)
if (value.length > 0) {
const status = value[0];
const paperOut = (status & 0x20) !== 0;
const drawerOpen = (status & 0x04) !== 0;
console.log(`Paper out: ${paperOut}, Drawer open: ${drawerOpen}`);
}
});
```
--------------------------------
### Initialize Printer Instance
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
Create a new printer instance using default or custom serial port configuration settings.
```javascript
// Basic initialization with default settings
const receiptPrinter = new WebSerialReceiptPrinter();
// Custom configuration for specific printer requirements
const receiptPrinter = new WebSerialReceiptPrinter({
baudRate: 115200,
bufferSize: 255,
dataBits: 8,
flowControl: 'none',
parity: 'none',
stopBits: 1
});
```
--------------------------------
### Constructor - WebSerialReceiptPrinter
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
Initializes a new printer instance with configurable serial port settings.
```APIDOC
## Constructor
### Description
Creates a new printer instance with configurable serial port settings.
### Parameters
- **options** (object) - Optional - Configuration object containing:
- **baudRate** (number) - Optional - Default 9600
- **bufferSize** (number) - Optional - Default 255
- **dataBits** (number) - Optional - 7 or 8, default 8
- **flowControl** (string) - Optional - 'none' or 'hardware'
- **parity** (string) - Optional - 'none', 'even', or 'odd'
- **stopBits** (number) - Optional - 1 or 2
### Request Example
const receiptPrinter = new WebSerialReceiptPrinter({
baudRate: 115200,
bufferSize: 255,
dataBits: 8,
flowControl: 'none',
parity: 'none',
stopBits: 1
});
```
--------------------------------
### Instantiate WebSerialReceiptPrinter
Source: https://github.com/nielsleenheer/webserialreceiptprinter/blob/main/README.md
Initialize the printer object using either a script tag or an ES module import.
```html
```
```js
import WebSerialReceiptPrinter from 'webserial-receipt-printer.esm.js';
const receiptPrinter = new WebSerialReceiptPrinter();
```
--------------------------------
### connect()
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
Initiates a connection to a serial port via the browser's native port picker.
```APIDOC
## connect()
### Description
Prompts the user to select a serial port through the browser's native port picker dialog. Must be called as a result of a user gesture.
### Request Example
await receiptPrinter.connect();
```
--------------------------------
### Implement Full Receipt Printing Workflow
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
A complete HTML implementation featuring connection management, persistent storage for auto-reconnection, and receipt generation using ReceiptPrinterEncoder.
```html
Receipt Printer Demo
Not connected
```
--------------------------------
### Configure Serial Port Settings
Source: https://github.com/nielsleenheer/webserialreceiptprinter/blob/main/README.md
Pass an options object during instantiation to override default serial port parameters like baud rate.
```js
const receiptPrinter = new WebSerialReceiptPrinter({
baudRate: 9600
});
```
--------------------------------
### Connect to Printer
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
Initiate a connection via the browser's native port picker. This must be triggered by a user gesture.
```javascript
const receiptPrinter = new WebSerialReceiptPrinter({ baudRate: 9600 });
// Attach to a button click handler
document.getElementById('connectBtn').addEventListener('click', async () => {
try {
await receiptPrinter.connect();
console.log('Connection initiated');
} catch (error) {
console.error('Connection failed:', error);
}
});
```
--------------------------------
### Listen for Connection Events
Source: https://github.com/nielsleenheer/webserialreceiptprinter/blob/main/README.md
Handle the 'connected' event to retrieve device information and store it for future reconnection.
```js
receiptPrinter.addEventListener('connected', device => {
console.log(`Connected to a device with vendorId: ${device.vendorId} and productId: ${device.productId}`);
/* Store device for reconnecting */
lastUsedDevice = device;
});
```
--------------------------------
### Connect to Printer
Source: https://github.com/nielsleenheer/webserialreceiptprinter/blob/main/README.md
Trigger the connection process via a user-initiated event such as a button click.
```js
function handleConnectButtonClick() {
receiptPrinter.connect();
}
```
--------------------------------
### Reconnect to Printer
Source: https://github.com/nielsleenheer/webserialreceiptprinter/blob/main/README.md
Automatically reconnect to a previously used USB device by providing its vendor and product IDs.
```js
receiptPrinter.reconnect(lastUsedDevice);
```
--------------------------------
### addEventListener() - Event Handling
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
Registers callbacks for printer events including connection status and incoming data.
```APIDOC
## addEventListener(type, callback)
### Description
Registers a callback function for specific printer events.
### Parameters
- **type** (string) - Required - The event name: 'connected', 'disconnected', or 'data'.
- **callback** (function) - Required - The function to execute when the event fires.
### Events
- **connected**: Fires when connection is established. Returns device info object.
- **disconnected**: Fires when connection is lost.
- **data**: Fires when data is received from the printer. Returns Uint8Array.
```
--------------------------------
### reconnect()
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
Attempts to automatically reconnect to a previously connected printer.
```APIDOC
## reconnect()
### Description
Allows automatic reconnection to a previously connected printer without user interaction.
### Parameters
- **device** (object) - Required - Object containing vendorId and productId.
### Request Example
receiptPrinter.reconnect({ vendorId: 1234, productId: 5678 });
```
--------------------------------
### Register Event Callbacks with addEventListener()
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
Registers handlers for printer lifecycle events including 'connected', 'disconnected', and 'data'.
```javascript
const receiptPrinter = new WebSerialReceiptPrinter({ baudRate: 9600 });
// Handle successful connection
receiptPrinter.addEventListener('connected', (device) => {
console.log('Connected to printer');
console.log('Connection type:', device.type); // 'serial'
console.log('Vendor ID:', device.vendorId); // USB vendor ID or null
console.log('Product ID:', device.productId); // USB product ID or null
document.getElementById('status').textContent = 'Connected';
document.getElementById('printBtn').disabled = false;
});
// Handle disconnection
receiptPrinter.addEventListener('disconnected', () => {
console.log('Printer disconnected');
document.getElementById('status').textContent = 'Disconnected';
document.getElementById('printBtn').disabled = true;
});
// Handle incoming data from printer
receiptPrinter.addEventListener('data', (data) => {
console.log('Received:', new Uint8Array(data));
});
```
--------------------------------
### Print a receipt using Web Serial
Source: https://github.com/nielsleenheer/webserialreceiptprinter/blob/main/README.md
Encodes receipt data using the ReceiptPrinterEncoder and sends it to the printer via the print function.
```js
/* Encode the receipt */
let encoder = new ReceiptPrinterEncoder({
language: 'esc-pos',
codepageMapping: 'epson'
});
let data = encoder
.initialize()
.text('The quick brown fox jumps over the lazy dog')
.newline()
.qrcode('https://nielsleenheer.com')
.encode();
/* Print the receipt */
receiptPrinter.print(data);
```
--------------------------------
### print() - Send Print Data
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
The print() method sends encoded receipt data to the printer. It accepts an array or typed array of bytes that must be pre-encoded.
```APIDOC
## print(data)
### Description
Sends encoded receipt data to the printer. Commands are queued internally and processed sequentially.
### Parameters
- **data** (Array|TypedArray) - Required - The pre-encoded byte data to be sent to the printer.
### Request Example
```javascript
const data = encoder.initialize().text('RECEIPT').encode();
await receiptPrinter.print(data);
```
```
--------------------------------
### Send Print Data with print()
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
Sends pre-encoded byte data to the printer. Data must be encoded using a library like ReceiptPrinterEncoder before transmission.
```javascript
import WebSerialReceiptPrinter from '@point-of-sale/webserial-printer';
import ReceiptPrinterEncoder from '@nicmanlabs/receipt-printer-encoder';
const receiptPrinter = new WebSerialReceiptPrinter({ baudRate: 9600 });
receiptPrinter.addEventListener('connected', async () => {
// Create encoder for ESC/POS compatible printer
const encoder = new ReceiptPrinterEncoder({
language: 'esc-pos',
codepageMapping: 'epson'
});
// Build the receipt
const data = encoder
.initialize()
.align('center')
.bold(true)
.text('RECEIPT')
.bold(false)
.newline()
.align('left')
.text('Item 1 $10.00')
.newline()
.text('Item 2 $5.50')
.newline()
.text('--------------------------------')
.newline()
.bold(true)
.text('Total $15.50')
.bold(false)
.newline()
.newline()
.qrcode('https://example.com/receipt/12345')
.newline()
.cut()
.encode();
// Send to printer
await receiptPrinter.print(data);
});
```
--------------------------------
### disconnect()
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
Gracefully closes the active serial port connection.
```APIDOC
## disconnect()
### Description
Gracefully closes the serial port connection, cancels pending read operations, and emits a 'disconnected' event.
### Request Example
await receiptPrinter.disconnect();
```
--------------------------------
### Disconnect from Printer
Source: https://context7.com/nielsleenheer/webserialreceiptprinter/llms.txt
Gracefully close the serial port connection and handle the disconnected event.
```javascript
const receiptPrinter = new WebSerialReceiptPrinter();
receiptPrinter.addEventListener('disconnected', () => {
console.log('Printer disconnected');
document.getElementById('status').textContent = 'Disconnected';
});
document.getElementById('disconnectBtn').addEventListener('click', async () => {
await receiptPrinter.disconnect();
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.