Skip to content

Instantly share code, notes, and snippets.

@BiosBoy
Created August 24, 2024 06:52
Show Gist options
  • Save BiosBoy/c9478c35ba94a7512bb52c125e31d996 to your computer and use it in GitHub Desktop.
Save BiosBoy/c9478c35ba94a7512bb52c125e31d996 to your computer and use it in GitHub Desktop.
# Code Examples from "Top 5 Underestimated Native Browser Features You Should Be Using"
## 1. Bluetooth: Connecting to Devices Wirelessly 📡
### Example: Connecting to a Bluetooth Device
```typescript
async function connectToBluetooth() {
try {
const device = await navigator.bluetooth.requestDevice({
filters: [{ services: ['battery_service'] }]
});
const server = await device.gatt?.connect();
const service = await server?.getPrimaryService('battery_service');
const characteristic = await service?.getCharacteristic('battery_level');
const batteryLevel = await characteristic?.readValue();
console.log('Battery level:', batteryLevel?.getUint8(0));
} catch (error) {
console.error('Bluetooth connection failed', error);
}
}
connectToBluetooth();
```
## 2. Camera Access: Beyond Just Selfies 📸
### Example: Capturing Video Stream
```typescript
async function startVideo() {
const videoElement = document.querySelector('video');
try {
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
videoElement.srcObject = stream;
} catch (error) {
console.error('Error accessing the camera', error);
}
}
startVideo();
```
## 3. Microphone: Adding Voice Interaction to Your Apps 🎤
### Example: Capturing Audio and Converting to Text
```typescript
function startVoiceRecognition() {
const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
console.log('You said:', transcript);
};
recognition.start();
}
startVoiceRecognition();
```
## 4. Geolocation: Not Just for Maps Anymore 🌍
### Example: Getting User Location
```typescript
function getLocation() {
navigator.geolocation.getCurrentPosition((position) => {
console.log('Latitude:', position.coords.latitude);
console.log('Longitude:', position.coords.longitude);
}, (error) => {
console.error('Error getting location', error);
});
}
getLocation();
```
## 5. Battery Status API: Optimize for Battery Life 🔋
### Example: Monitoring Battery Status
```typescript
async function monitorBattery() {
const battery = await navigator.getBattery();
function updateBatteryStatus() {
console.log(`Battery Level: ${battery.level * 100}%`);
console.log(`Is Charging: ${battery.charging}`);
}
updateBatteryStatus();
battery.addEventListener('levelchange', updateBatteryStatus);
battery.addEventListener('chargingchange', updateBatteryStatus);
}
monitorBattery();
```
## 6. Web NFC API: Tap into the World of Near Field Communication 📱
### Example: Reading an NFC Tag
```typescript
async function readNFC() {
try {
const nfcReader = new NDEFReader();
await nfcReader.scan();
nfcReader.onreading = (event) => {
const message = event.message.records[0];
console.log('NFC Tag content:', message.data);
};
} catch (error) {
console.error('NFC reading failed', error);
}
}
readNFC();
```
## 7. Payment Request API: Simplifying Online Payments 💳
### Example: Initiating a Payment Request
```typescript
async function initiatePayment() {
const supportedInstruments = [{
supportedMethods: 'basic-card',
data: {
supportedNetworks: ['visa', 'mastercard']
}
}];
const details = {
total: { label: 'Total', amount: { currency: 'USD', value: '10.00' } }
};
try {
const request = new PaymentRequest(supportedInstruments, details);
const paymentResponse = await request.show();
await paymentResponse.complete('success');
console.log('Payment successful', paymentResponse);
} catch (error) {
console.error('Payment failed', error);
}
}
initiatePayment();
```
## 8. Web Share API: Enable Social Sharing Natively 🔗
### Example: Sharing a URL
```typescript
function shareContent() {
if (navigator.share) {
navigator.share({
title: 'Check this out!',
text: 'This is an awesome website!',
url: 'https://example.com',
})
.then(() => console.log('Content shared successfully'))
.catch((error) => console.error('Error sharing content', error));
} else {
console.log('Web Share API is not supported in this browser');
}
}
shareContent();
```
## 9. Clipboard API: Access the User’s Clipboard Directly ✂️
### Example: Copying Text to Clipboard
```typescript
async function copyToClipboard(text: string) {
try {
await navigator.clipboard.writeText(text);
console.log('Text copied to clipboard');
} catch (error) {
console.error('Failed to copy text', error);
}
}
copyToClipboard('Hello, World!');
```
## 10. Device Orientation API: Create Interactive Experiences Based on Device Movement 📱
### Example: Detecting Device Orientation
```typescript
function handleOrientation(event: DeviceOrientationEvent) {
console.log('Alpha (Z-axis):', event.alpha);
console.log('Beta (X-axis):', event.beta);
console.log('Gamma (Y-axis):', event.gamma);
}
window.addEventListener('deviceorientation', handleOrientation);
```
## 11. Vibration API: Feel the Buzz 📳
### Example: Simple Vibration
```typescript
function vibrateDevice() {
if (navigator.vibrate) {
navigator.vibrate(200); // Vibrates for 200 milliseconds
console.log('Device vibrated');
} else {
console.log('Vibration API not supported');
}
}
vibrateDevice();
```
### Example: Patterned Vibration
```typescript
function vibratePattern() {
if (navigator.vibrate) {
navigator.vibrate([100, 200, 100, 200, 500]); // Vibration pattern: vibrate, pause, vibrate, pause, long vibrate
console.log('Device vibrated in pattern');
} else {
console.log('Vibration API not supported');
}
}
vibratePattern();
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment