Skip to content
Back to Docs

NativeBridge API

Access native device features from your website using JavaScript. Available in all WebView-based apps built with Code2Native.

3 MIN

Add Face ID Login to Your Website

Turn any login form into a biometric-secured experience. Works on iPhone (Face ID), iPad (Touch ID), and Android (Fingerprint).

1Detect native environment
// Add this to your login page
const isNativeApp = typeof Code2Native !== 'undefined' && Code2Native.isNative();
2Show biometric button if available
// Check biometric availability
if (isNativeApp && Code2Native.canUseBiometric() === 'available') {
  document.getElementById('biometric-btn').style.display = 'block';
}
3Authenticate on button click
document.getElementById('biometric-btn').onclick = async () => {
  try {
    await Code2Native.authenticateBiometric({ 
      title: 'Sign In',
      subtitle: 'Use Face ID to access your account'
    });
    // Success! Load saved token and auto-login
    const token = Code2Native.getStorageItem('authToken');
    if (token) loginWithToken(token);
  } catch (e) {
    console.log('Biometric cancelled or failed');
  }
};

💡 Pro Tip: Once you add this code, your website automatically gets biometric login in the native app—no Xcode or Android Studio required!

Device & System

isNative()
AndroidiOS

Check if running inside Code2Native app

Returns: boolean

if (Code2Native.isNative()) { ... }
getDeviceInfo()
AndroidiOS

Get device platform, model, OS version

Returns: { platform, model, appVersion } on both platforms; Android adds manufacturer, sdkVersion, brand, release, isEmulator, packageName; iOS adds systemVersion

const info = Code2Native.getDeviceInfo();
console.log(info.platform); // 'android' or 'ios'
isOnline()
Android

Check network connectivity. iOS: use navigator.onLine

Returns: boolean

if (Code2Native.isOnline()) { sync(); }
getNetworkType()
Android

Get current network type

Returns: 'wifi' | 'cellular' | 'ethernet' | 'none'

if (Code2Native.getNetworkType() === 'wifi') { downloadLargeFile(); }
getBatteryLevel()
Android

Get battery percentage (0-100)

Returns: number

const battery = Code2Native.getBatteryLevel();

UI Feedback

showToast(message)
AndroidiOS

Show native toast notification

Code2Native.showToast('Saved successfully');
vibrate(ms)
AndroidiOS

Trigger haptic vibration

Code2Native.vibrate(50); // Light tap
vibratePattern(pattern)
Android

Vibrate with custom pattern

Code2Native.vibratePattern([0, 100, 50, 100]); // SOS pattern

Sharing & Clipboard

share(text, title?)
AndroidiOS

Open native share sheet

Code2Native.share('Check this out!', 'Share');
copyToClipboard(text)
AndroidiOS

Copy text to system clipboard

Code2Native.copyToClipboard('ABC123');

Navigation

openSettings()
AndroidiOS

Open app settings page

Code2Native.openSettings();
openUrl(url)
AndroidiOS

Open URL (iOS uses in-app WebView for http/https; Android opens external browser)

Code2Native.openUrl('https://example.com');
openEmail(email, subject?, body?)
Android

Open email composer. On iOS use openUrl('mailto:...')

Code2Native.openEmail('[email protected]', 'Help', 'I need help with...');
openPhone(number)
Android

Open phone dialer. On iOS use openUrl('tel:...')

Code2Native.openPhone('+1234567890');

Secure Storage

setStorageItem(key, value)
AndroidiOS

Store encrypted data (Keychain on iOS, EncryptedSharedPrefs on Android)

Code2Native.setStorageItem('authToken', 'eyJhbG...');
getStorageItem(key)
AndroidiOS

Retrieve stored data

Returns: string

const token = Code2Native.getStorageItem('authToken');
removeStorageItem(key)
AndroidiOS

Delete stored item

Code2Native.removeStorageItem('authToken');

Biometric Authentication

canUseBiometric()
AndroidiOS

Check biometric availability. iOS always reports 'available' — real availability is checked at prompt time

Returns: 'available' | 'no_hardware' | 'hardware_unavailable' | 'not_enrolled' | 'disabled' | 'unknown' (Android)

if (Code2Native.canUseBiometric() === 'available') { ... }
authenticateBiometric(options)
AndroidiOS

Prompt Face ID, Touch ID, or Fingerprint

Returns: Promise<{ success: boolean }>

try {
  await Code2Native.authenticateBiometric({ title: 'Confirm Payment' });
  // Success
} catch (e) {
  // User cancelled or failed
}

Location

getCurrentLocation()
AndroidiOS

Get GPS coordinates (requires permission)

Returns: Promise<{ latitude, longitude, accuracy }>

const loc = await Code2Native.getCurrentLocation();
console.log(loc.latitude, loc.longitude);

Camera & Scanner

takePhoto()
AndroidiOS

Capture photo using camera

Returns: Promise<{ uri: string }>

const photo = await Code2Native.takePhoto();
uploadImage(photo.uri);
scanQRCode()
AndroidiOS

Scan QR code or barcode

Returns: Promise<{ value: string, format: string }>

const result = await Code2Native.scanQRCode();
console.log('Scanned:', result.value);

iOS-Only Features

signInWithApple()
iOS

Sign in with Apple authentication

Returns: Promise<{ user, email, fullName }>

const apple = await Code2Native.signInWithApple();
sendToBackend(apple.user, apple.email);
setBadge(count)
iOS

Set app icon badge number

Code2Native.setBadge(5); // Show '5' on app icon
downloadFile(url, filename?)
iOS

Download file and show share sheet

Code2Native.downloadFile('https://example.com/report.pdf', 'report.pdf');

Dark Mode

isDarkMode()
iOS

Check if system dark mode is enabled

Returns: boolean

if (Code2Native.isDarkMode()) {
  document.body.classList.add('dark');
}

Background Sync

scheduleBackgroundSync(interval?, requiresWifi?)
AndroidiOS

Schedule periodic background sync tasks

Code2Native.scheduleBackgroundSync(15, false);
cancelBackgroundSync()
AndroidiOS

Cancel scheduled background sync

Code2Native.cancelBackgroundSync();
syncNow()
AndroidiOS

Trigger immediate background sync

Returns: Promise<{ success: boolean }>

const result = await Code2Native.syncNow();
console.log('Sync success:', result.success);
getLastSyncTime()
AndroidiOS

Get timestamp of last successful sync

Returns: { timestamp: number, iso: string }

const sync = Code2Native.getLastSyncTime();
console.log('Last sync:', sync.iso);
isBackgroundSyncScheduled()
Android

Check if background sync is currently scheduled

Returns: boolean

if (Code2Native.isBackgroundSyncScheduled()) {
  console.log('Sync is running');
}

Widget Control

updateWidgetContent(title, subtitle)
AndroidiOS

Update home screen widget content

Code2Native.updateWidgetContent('New Message', 'You have 3 unread items');
refreshWidget()
AndroidiOS

Force refresh all home screen widgets

Code2Native.refreshWidget();

Screen Orientation

lockOrientation(orientation)
AndroidiOS

Lock screen to specific orientation. Useful for video players, games, or data tables.

// Lock to landscape for video playback
Code2Native.lockOrientation('landscape');

// Lock to portrait for forms
Code2Native.lockOrientation('portrait');
unlockOrientation()
AndroidiOS

Remove orientation lock, allow free rotation

Code2Native.unlockOrientation();
getOrientation()
AndroidiOS

Get current screen orientation

Returns: 'portrait' | 'landscape' | Promise<string> (iOS)

const orientation = Code2Native.getOrientation();
console.log('Current:', orientation); // 'portrait' or 'landscape'

In-App Browser

openInAppBrowser(url, options?)
AndroidiOS

Open URL in an in-app browser (SFSafariViewController on iOS, Chrome Custom Tabs on Android). Keeps user inside your app.

// Basic usage
Code2Native.openInAppBrowser('https://docs.example.com');

// With Reader Mode (iOS)
Code2Native.openInAppBrowser('https://article.com', { readerMode: true });

Push Notifications

getPushToken()
AndroidiOS

Get the push notification device token. Useful for associating users on your backend.

Returns: string (Android) | Promise<string> (iOS)

const token = await Code2Native.getPushToken();
if (token) {
  fetch('/api/register-device', {
    method: 'POST',
    body: JSON.stringify({ token, userId: currentUser.id })
  });
}
isPushEnabled()
Android

Check if push notifications are enabled for this device

Returns: boolean

if (!Code2Native.isPushEnabled()) {
  showPushEnablePrompt();
}
requestPushPermission()
Android

Request push notification permission from user (Android)

Code2Native.requestPushPermission();

App Tracking Transparency (iOS)

requestTrackingPermission()
AndroidiOS

Request iOS 14+ App Tracking Transparency authorization. Required for IDFA access and personalized ads. Android returns 'not_required' immediately.

Returns: Promise<{ success: boolean, status: string }>

const result = await Code2Native.requestTrackingPermission();
console.log(result.status);
// iOS: 'authorized' | 'denied' | 'restricted' | 'not_determined'
// Android: 'not_required'
getTrackingStatus()
AndroidiOS

Get current tracking authorization status without prompting user

Returns: Promise<{ status: string }> | { status: string }

const status = await Code2Native.getTrackingStatus();
if (status.status === 'authorized') {
  loadPersonalizedAds();
} else {
  loadGenericAds();
}

Events

code2nativeready

Fired when bridge initialization is complete. Use this to ensure APIs are available.

window.addEventListener('code2nativeready', () => {
  console.log('Bridge ready!');
  initApp();
});
code2native:darkModeChangediOS

Fired when user toggles system dark mode. iOS only — the Android template does not fire this event (consistent with isDarkMode()).

window.addEventListener('code2native:darkModeChanged', (e) => {
  if (e.detail.isDark) {
    document.body.classList.add('dark');
  } else {
    document.body.classList.remove('dark');
  }
});

Limitations

  • APIs only work inside Code2Native WebView apps (not in regular browsers)
  • Clipboard read is disabled on all platforms for security — use copyToClipboard for write-only access
  • Location, camera, QR require user permission grants
  • Sign in with Apple is iOS-only
  • App Tracking Transparency (ATT) only applies on iOS 14+; Android returns 'not_required'
  • Push notifications require OneSignal configuration in project settings
  • Screen orientation lock may behave differently on tablets vs phones
  • In-app browser uses system Chrome/Safari, appearance follows OS settings