0.0.1 • Published 12 months ago
@aya-mash/web-nfc-api v0.0.1
@aya-mash/web-nfc-api
A TypeScript library for working with the Web NFC API in modern browsers.
Installation
npm install @aya-mash/web-nfc-apiUsage
import { WebNFC } from '@aya-mash/web-nfc-api';
const nfc = WebNFC.getInstance();
// Check if NFC is supported
if (nfc.isSupported()) {
try {
// Request permission
const permission = await nfc.requestPermission();
// Start scanning
await nfc.startScanning();
// Listen for NFC readings
nfc.onReading((message) => {
console.log('NFC message:', message);
});
// Handle reading errors
nfc.onReadingError((error) => {
console.error('NFC error:', error);
});
// Write to NFC tag
await nfc.write({
records: [{
recordType: 'text',
data: 'Hello from Web NFC!'
}]
});
} catch (error) {
console.error('NFC operation failed:', error);
}
}Features
- 🔒 TypeScript support with full type definitions
- 🎯 Simple, intuitive API
- 🔄 Singleton pattern for consistent NFC access
- ⚡ Async/await support
- 🛡️ Error handling
- 📱 Permission management
Requirements
- Chrome for Android (version 89 or later)
- HTTPS connection (except for localhost)
- Device with NFC hardware
API Reference
WebNFC
getInstance()
Returns the singleton instance of the WebNFC class.
const nfc = WebNFC.getInstance();isSupported()
Checks if Web NFC API is supported in the current browser.
const supported = nfc.isSupported();requestPermission()
Requests NFC permission from the user.
const permission = await nfc.requestPermission();startScanning(options?: NFCReadOptions)
Starts scanning for NFC tags.
await nfc.startScanning();write(message: NFCMessage, options?: NFCWriteOptions)
Writes data to an NFC tag.
await nfc.write({
records: [{
recordType: 'text',
data: 'Hello, NFC!'
}]
});onReading(callback: (message: NFCMessage) => void)
Sets up a callback for when an NFC tag is read.
nfc.onReading((message) => {
console.log('Tag read:', message);
});onReadingError(callback: (error: Error) => void)
Sets up a callback for handling reading errors.
nfc.onReadingError((error) => {
console.error('Reading error:', error);
});License
MIT
0.0.1
12 months ago