NativeBridge API
Access native device features from your website using JavaScript. Available in all WebView-based apps built with Code2Native.
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).
// Add this to your login page const isNativeApp = typeof Code2Native !== 'undefined' && Code2Native.isNative();
// Check biometric availability
if (isNativeApp && Code2Native.canUseBiometric() === 'available') {
document.getElementById('biometric-btn').style.display = 'block';
}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()Check if running inside Code2Native app
Returns: boolean
if (Code2Native.isNative()) { ... }getDeviceInfo()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()Check network connectivity. iOS: use navigator.onLine
Returns: boolean
if (Code2Native.isOnline()) { sync(); }getNetworkType()Get current network type
Returns: 'wifi' | 'cellular' | 'ethernet' | 'none'
if (Code2Native.getNetworkType() === 'wifi') { downloadLargeFile(); }getBatteryLevel()Get battery percentage (0-100)
Returns: number
const battery = Code2Native.getBatteryLevel();
UI Feedback
showToast(message)Show native toast notification
Code2Native.showToast('Saved successfully');vibrate(ms)Trigger haptic vibration
Code2Native.vibrate(50); // Light tap
vibratePattern(pattern)Vibrate with custom pattern
Code2Native.vibratePattern([0, 100, 50, 100]); // SOS pattern
Sharing & Clipboard
share(text, title?)Open native share sheet
Code2Native.share('Check this out!', 'Share');copyToClipboard(text)Copy text to system clipboard
Code2Native.copyToClipboard('ABC123');Navigation
openSettings()Open app settings page
Code2Native.openSettings();
openUrl(url)Open URL (iOS uses in-app WebView for http/https; Android opens external browser)
Code2Native.openUrl('https://example.com');openEmail(email, subject?, body?)Open email composer. On iOS use openUrl('mailto:...')
Code2Native.openEmail('[email protected]', 'Help', 'I need help with...');openPhone(number)Open phone dialer. On iOS use openUrl('tel:...')
Code2Native.openPhone('+1234567890');Secure Storage
setStorageItem(key, value)Store encrypted data (Keychain on iOS, EncryptedSharedPrefs on Android)
Code2Native.setStorageItem('authToken', 'eyJhbG...');getStorageItem(key)Retrieve stored data
Returns: string
const token = Code2Native.getStorageItem('authToken');removeStorageItem(key)Delete stored item
Code2Native.removeStorageItem('authToken');Biometric Authentication
canUseBiometric()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)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()Get GPS coordinates (requires permission)
Returns: Promise<{ latitude, longitude, accuracy }>
const loc = await Code2Native.getCurrentLocation(); console.log(loc.latitude, loc.longitude);
Camera & Scanner
takePhoto()Capture photo using camera
Returns: Promise<{ uri: string }>
const photo = await Code2Native.takePhoto(); uploadImage(photo.uri);
scanQRCode()Scan QR code or barcode. Turn on the camera feature for this: on Android, apps without it leave the scanner out (up to 20 MB smaller as a direct APK) and answer DISABLED.
Returns: Promise<{ value: string, format: string }>
const result = await Code2Native.scanQRCode();
console.log('Scanned:', result.value);iOS-Only Features
signInWithApple()Sign in with Apple authentication. Needs Apple's Sign in with Apple entitlement: IPAs signed by Code2Native do not carry it; if you sign the unsigned IPA yourself, your provisioning profile must include the capability and your signing tool must apply it.
Returns: Promise<{ user, email, fullName }>
const apple = await Code2Native.signInWithApple(); sendToBackend(apple.user, apple.email);
setBadge(count)Set app icon badge number
Code2Native.setBadge(5); // Show '5' on app icon
downloadFile(url, filename?)Download file and show share sheet
Code2Native.downloadFile('https://example.com/report.pdf', 'report.pdf');Dark Mode
isDarkMode()Check if system dark mode is enabled
Returns: boolean
if (Code2Native.isDarkMode()) {
document.body.classList.add('dark');
}Background Sync
scheduleBackgroundSync(interval?, requiresWifi?)Schedule periodic background sync tasks
Code2Native.scheduleBackgroundSync(15, false);
cancelBackgroundSync()Cancel scheduled background sync
Code2Native.cancelBackgroundSync();
syncNow()Trigger immediate background sync
Returns: Promise<{ success: boolean }>
const result = await Code2Native.syncNow();
console.log('Sync success:', result.success);getLastSyncTime()Get timestamp of last successful sync
Returns: { timestamp: number, iso: string }
const sync = Code2Native.getLastSyncTime();
console.log('Last sync:', sync.iso);isBackgroundSyncScheduled()Check if background sync is currently scheduled
Returns: boolean
if (Code2Native.isBackgroundSyncScheduled()) {
console.log('Sync is running');
}Widget Control
updateWidgetContent(title, subtitle)Update home screen widget content
Code2Native.updateWidgetContent('New Message', 'You have 3 unread items');refreshWidget()Force refresh all home screen widgets
Code2Native.refreshWidget();
Screen Orientation
lockOrientation(orientation)Lock screen to specific orientation. Useful for video players, games, or data tables. On Android 16 and later, phones honour it, but screens whose smallest width is 600 dp or more (tablets, unfolded foldables) ignore it for apps targeting API 36, as Google Play's builds now do.
// Lock to landscape for video playback
Code2Native.lockOrientation('landscape');
// Lock to portrait for forms
Code2Native.lockOrientation('portrait');unlockOrientation()Remove orientation lock, allow free rotation
Code2Native.unlockOrientation();
getOrientation()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?)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()Get the push notification device token (Android). Useful for associating users on your backend.
Returns: string
const token = await Code2Native.getPushToken();
if (token) {
fetch('/api/register-device', {
method: 'POST',
body: JSON.stringify({ token, userId: currentUser.id })
});
}isPushEnabled()Check if push notifications are enabled for this device
Returns: boolean
if (!Code2Native.isPushEnabled()) {
showPushEnablePrompt();
}requestPushPermission()Ask for push notification permission (Android). Apps built after September 28, 2026 already ask once, the first time they open, when push is set up; older builds ask only when your site calls this. Use it after someone declined, e.g. from a "Turn on notifications" button
Code2Native.requestPushPermission();
App Tracking Transparency (iOS)
requestTrackingPermission()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()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
code2nativereadyFired when bridge initialization is complete. Use this to ensure APIs are available.
window.addEventListener('code2nativeready', () => {
console.log('Bridge ready!');
initApp();
});code2native:darkModeChangediOSFired 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