API Reference

Complete guide to 29+ native bridge methods

Location

getLocation()

Retrieves the device's current GPS coordinates with accuracy information.

Returns
Promise<LocationResult>
{
  lat: number,      // Latitude
  lng: number,      // Longitude
  accuracy: number  // Accuracy in meters
}
Example
const location = await bridge.getLocation();
console.log(`Lat: ${location.lat}, Lng: ${location.lng}`);
// In Vue component
export default {
  data() {
    return { location: null }
  },
  async mounted() {
    this.location = await bridge.getLocation();
    console.log(`Lat: ${this.location.lat}`);
  }
}
// In React component
import { useState, useEffect } from 'react';

function LocationComponent() {
  const [location, setLocation] = useState(null);
  
  useEffect(() => {
    bridge.getLocation().then(loc => {
      setLocation(loc);
      console.log(`Lat: ${loc.lat}`);
    });
  }, []);
  
  return 
Location loaded
; }
calculateDistance(lat1, lng1, lat2, lng2)

두 지점 간의 거리를 계산합니다. (Calculate distance between two points)

Parameters
Returns
Promise<{ distance: number }> - 거리 (미터) / Distance in meters
Example
const result = await bridge.calculateDistance(37.5, 127.0, 37.6, 127.1);
console.log(`거리: ${result.distance}m`);
watchLocation(callback) / stopWatchLocation(watcher)

Starts or stops real-time continuous GPS location monitoring updates.

Example
const watcher = await bridge.watchLocation((loc) => {
  console.log(`Updated Lat: ${loc.lat}, Lng: ${loc.lng}`);
});
// To stop:
await bridge.stopWatchLocation(watcher);

Camera & Gallery

takePhoto()

Opens the device camera to capture a photo.

Returns
Promise<string> - Base64 encoded image
Example
const photo = await bridge.takePhoto();
document.getElementById('img').src = `data:image/jpeg;base64,${photo}`;
// In Vue component
<template>
  <img :src="photoSrc" alt="Photo" />
</template>

<script>
export default {
  data() {
    return { photoSrc: '' }
  },
  methods: {
    async takePhoto() {
      const photo = await bridge.takePhoto();
      this.photoSrc = `data:image/jpeg;base64,${photo}`;
    }
  }
}
</script>
import { useState } from 'react';

function PhotoComponent() {
  const [photoSrc, setPhotoSrc] = useState('');
  
  const takePhoto = async () => {
    const photo = await bridge.takePhoto();
    setPhotoSrc(`data:image/jpeg;base64,${photo}`);
  };
  
  return (
    
Photo
); }
pickImage()

Opens the gallery to select an existing image.

Returns
Promise<string> - Base64 encoded image
Example
const image = await bridge.pickImage();
document.getElementById('preview').src = `data:image/jpeg;base64,${image}`;
methods: {
  async selectImage() {
    const image = await bridge.pickImage();
    this.imageSrc = `data:image/jpeg;base64,${image}`;
  }
}
const selectImage = async () => {
  const image = await bridge.pickImage();
  setImageSrc(`data:image/jpeg;base64,${image}`);
};
pickVideo()

Opens the gallery to select an existing video file.

Returns
Promise<{ videoUrl: string }>
Example
const res = await bridge.pickVideo();
console.log(`Video URL: ${res.videoUrl}`);

Notifications

registerPushUser(target) / unregisterPushUser(target)

토큰 획득과 익명 설치는 준비 단계이며, 로그인 사용자를 연결할 때는 고객 백엔드가 발급한 일회성 registrationProof가 필요합니다. 등록/해제와 사용량 과금이 적용되는 발송은 별개입니다.

Parameters
  • appIdstring (optional)
    콘솔 앱 UUID. 기본값은 앱 빌드 설정이며, 명시하면 증명에 연결된 앱과 같아야 합니다. 소유자 userId는 전달하지 않습니다.
  • appUserIdstring
    고객 백엔드가 검증된 로그인 세션에서 결정한 사용자 ID입니다.
  • registrationProofstring
    로그인 사용자 등록용 5분·일회성 증명. appId·appUserId·현재 토큰에 결합되며, 해제에는 필요하지 않습니다.
Example
// 최신 WebBridge 인스턴스입니다. 실제 콘솔 앱 UUID를 사용하세요.
const expectedAppId = '22222222-2222-4222-8222-222222222222';
const { token } = await bridge.getFcmToken();

// 고객 서비스의 로그인 세션 및 CSRF를 검증하는 백엔드입니다.
const response = await fetch('/my-account/push-proof', {
  method: 'POST', credentials: 'same-origin',
  headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrfToken },
  body: JSON.stringify({ token })
});
if (!response.ok) throw new Error('푸시 등록 증명 발급 실패');
const { appId, appUserId, registrationProof } = await response.json();
if (appId !== expectedAppId || !appUserId || !registrationProof) {
  throw new Error('푸시 등록 대상 불일치');
}
await bridge.registerPushUser({ appId, appUserId, registrationProof });

// 로그아웃할 때 별도로 호출합니다.
async function onLogout() {
  await bridge.unregisterPushUser({ appId, appUserId });
}

/my-account/push-proof와 csrfToken은 고객 서비스에서 구현합니다. 백엔드는 허용 앱 설정과 로그인 세션으로 ID를 결정한 뒤 POST /api/notifications/registration-proof를 호출합니다. nv_ API 키와 설치형 shared secret은 백엔드에만 보관하고 브라우저·앱에 전달하지 않습니다. 일반 고객이 콘솔에 로그인할 필요는 없습니다.

익명 설치는 POST /api/notifications/install로 준비하며 기존 로그인 연결을 덮어쓰지 않습니다. 토큰 갱신 이벤트 pushRegistrationRequired나 증명 만료 시 현재 고객 세션으로 새 증명을 발급받습니다. 이전 proof를 저장하거나 재사용하지 마세요. 전체 연동 예시는 FCM 사용 가이드를 참고하세요.

showNotification(title, body)

Displays a local push notification with custom title and message.

Parameters
  • title string
    Notification title
  • body string
    Notification message body
Example
await bridge.showNotification('New Message', 'Hello from Nativify!');
// In Vue component
methods: {
  async notifyUser() {
    await bridge.showNotification('New Message', 'Hello!');
  }
}
const notifyUser = async () => {
  await bridge.showNotification('New Message', 'Hello!');
};

showToast(message)

Shows a brief toast message at the bottom of the screen.

Parameters
  • message string
    Message to display
Example
await bridge.showToast('Action completed successfully!');
methods: {
  async saveAndNotify() {
    await this.saveData();
    await bridge.showToast('Saved!');
  }
}
const handleSave = async () => {
  await saveData();
  await bridge.showToast('Saved!');
};

Storage

saveData(key, value)

Persists data to local storage. Values are automatically serialized to JSON.

Parameters
  • key string
    Storage key
  • value any
    Value to store (auto-serialized)
Example
await bridge.saveData('user', { id: 123, name: 'John' });
// In Vue component
await bridge.saveData('user', this.userInfo);

// Load data
this.userInfo = await bridge.loadData('user');
// Save user data
await bridge.saveData('user', userInfo);

// Load user data
const userInfo = await bridge.loadData('user');
setUserInfo(userInfo);
loadData(key) / deleteData(key)

Retrieves or deletes data from app local secure storage.

Example
const data = await bridge.loadData('user');
await bridge.deleteData('user');
Example
const userData = await bridge.loadData('user');
if (userData) {
  console.log('User:', userData.name);
}
async mounted() {
  this.userData = await bridge.loadData('user');
}
useEffect(() => {
  bridge.loadData('user').then(data => {
    setUserData(data);
  });
}, []);

Device Info

getDeviceInfo()

Returns comprehensive device and app information.

Returns
{
  platform: string,    // 'android' | 'ios'
  model: string,       // Device model
  version: string,     // OS version
  appVersion: string   // App version
}
Example
const info = await bridge.getDeviceInfo();
console.log(`Running on ${info.platform} ${info.version}`);
async mounted() {
  this.deviceInfo = await bridge.getDeviceInfo();
  console.log('Device:', this.deviceInfo.model);
}
const [deviceInfo, setDeviceInfo] = useState(null);

useEffect(() => {
  bridge.getDeviceInfo().then(setDeviceInfo);
}, []);
getVersionInfo()

Returns detailed app build and environment version info.

Returns
{
  runtime: string,    // Native runtime version
  kotlin: string,     // Kotlin version
  agp: string,        // Android Gradle Plugin version
  androidSdk: string, // Target Android SDK
  minSdkVersion: string
}
Example
const versions = await bridge.getVersionInfo();
console.log(`Runtime: ${versions.runtime}, Android SDK: ${versions.androidSdk}`);
async mounted() {
  this.versions = await bridge.getVersionInfo();
}
useEffect(() => {
  bridge.getVersionInfo().then(setVersions);
}, []);
getAppState()

앱의 현재 환경 정보를 얻습니다. (Get current app state/environment)

Returns
Promise<{ environment: string, isLocalhost: boolean, url: string }>
Example
const state = await bridge.getAppState();
console.log(state.environment);

Background Service New

updateTrackingNotification(title, text)

Updates background service notification title and text in real-time.

Parameters
  • title string
    Notification Title
  • text string
    Notification Text
Example
await bridge.updateTrackingNotification('Tracking Active', 'Currently at Gangnam Station');
checkBatteryOptimizations()

Check if the app is ignored from battery optimizations.

Returns
Promise<boolean>
requestBatteryOptimizations()

Request user to ignore battery optimizations for the app.

Returns
startTracking(options) / stopTracking()

Starts or stops persistent background GPS/step tracking service.

Example
await bridge.startTracking({ interval: 10000 });
await bridge.stopTracking();
getTrackingStatus() / getServiceHealth()

Queries background service running status and health check.

Example
const status = await bridge.getTrackingStatus();
const health = await bridge.getServiceHealth();
getActivityHistory() / clearHistory()

Queries activity tracking logs or clears history database logs.

Example
const history = await bridge.getActivityHistory({ limit: 10 });
await bridge.clearHistory();
enableBackground(enabled)

Ensures app process remains active in background.

Example
await bridge.enableBackground(true);

Health & Activity New

getSteps()

Request activity recognition permission and handle step count data.

Example
// Request permission and start tracking
await bridge.getSteps();

// Listen for step updates
window.onNativeData = (data) => {
  if (data.type === 'BACKGROUND_DATA' && data.payload.steps) {
    console.log(`Current steps: ${data.payload.steps}`);
  }
};
// In Vue component
async mounted() {
  await bridge.getSteps();
  
  window.onNativeData = (data) => {
    if (data.type === 'BACKGROUND_DATA') {
      this.steps = data.payload.steps;
    }
  };
}

Clipboard New

copyToClipboard(text)

Copies text to the system clipboard.

Parameters
  • text string
    Text to copy
Example
await bridge.copyToClipboard('Hello World');
console.log('Copied to clipboard!');
methods: {
  async copyText(text) {
    await bridge.copyToClipboard(text);
    this.showMessage('Copied!');
  }
}
const handleCopy = async (text) => {
  await bridge.copyToClipboard(text);
  setMessage('Copied!');
};
getClipboard()

Reads text from the system clipboard.

Returns
Promise<string> - Clipboard content
Example
const text = await bridge.getClipboard();
console.log('Clipboard:', text);
async mounted() {
  this.clipboardText = await bridge.getClipboard();
}
const pasteText = async () => {
  const text = await bridge.getClipboard();
  setText(text);
};

UI Control New

setStatusBar(options)

Customizes the status bar appearance including color and icon brightness.

Parameters
  • options.color string
    Hex color, 'transparent', or 'default'
  • options.brightness string
    'light' or 'dark'
Example
await bridge.setStatusBar({ color: '#667eea', brightness: 'light' });
async mounted() {
  await bridge.setStatusBar({ color: '#667eea', brightness: 'light' });
}
useEffect(() => {
  bridge.setStatusBar({ color: '#667eea', brightness: 'light' });
}, []);
setOrientation(orientation)

Controls screen orientation lock.

Parameters
  • orientation string
    'portrait', 'landscape', or 'any'
Example
await bridge.setOrientation('landscape');
methods: {
  async lockLandscape() {
    await bridge.setOrientation('landscape');
  }
}
const setLandscape = async () => {
  await bridge.setOrientation('landscape');
};
getSafeArea()

Returns safe area insets for devices with notches or rounded corners.

Returns
{
  top: number,    // Top inset (px)
  bottom: number, // Bottom inset (px)
  left: number,   // Left inset (px)
  right: number   // Right inset (px)
}
Example
const safeArea = await bridge.getSafeArea();
console.log('Top inset:', safeArea.top);
async mounted() {
  this.safeArea = await bridge.getSafeArea();
  this.applyPadding();
}
const [safeArea, setSafeArea] = useState(null);

useEffect(() => {
  bridge.getSafeArea().then(setSafeArea);
}, []);
showDialog(title, message, buttons) / openUrl(url)

Displays native modal dialog or opens URL in device browser.

Example
const res = await bridge.showDialog('Confirm', 'Proceed?', ['Cancel', 'OK']);
await bridge.openUrl('https://nativify.site');

⬇️File Download New

Nativify.downloadFile({ url, filename, mode })

Downloads a file with save/share/open handling. Relative legacy routes such as /common/file/fileDown resolve against the current web origin.

Parameters
  • url string
    Download URL
  • filename string
    Optional file name. Falls back to the URL path or download.
  • mode "save" | "share" | "open"
    open may degrade to share if the platform cannot open the file directly.
Returns
{
  path: string,
  filename: string,
  modeRequested: string,
  modeResolved: string
}
Example
const result = await Nativify.downloadFile({
  url: '/common/file/fileDown?atchFileId=123',
  filename: 'document.pdf',
  mode: 'share'
});
console.log('Saved to:', result.path);
data() {
  return { downloadProgress: 0 }
},
methods: {
  async download() {
    const result = await Nativify.downloadFile({
      url: 'https://example.com/file.pdf',
      filename: 'doc.pdf',
      mode: 'open'
    });
  }
}
const [progress, setProgress] = useState(0);

const download = async () => {
  const result = await Nativify.downloadFile({
    url: 'https://example.com/file.pdf',
    filename: 'doc.pdf',
    mode: 'save'
  });
};

Communication New

makePhoneCall(phoneNumber)

Opens the phone dialer with the specified number.

Parameters
  • phoneNumber string
    Phone number to call
Example
await bridge.makePhoneCall('010-1234-5678');
methods: {
  async callSupport() {
    await bridge.makePhoneCall(this.supportNumber);
  }
}
const callPhone = async (number) => {
  await bridge.makePhoneCall(number);
};
sendSMS(phoneNumber, message)

Opens the SMS app with pre-filled recipient and message.

Parameters
  • phoneNumber string | null
    Recipient number (optional)
  • message string
    SMS message content
Example
await bridge.sendSMS('010-1234-5678', 'Hello!');
methods: {
  async sendMessage() {
    await bridge.sendSMS(this.phoneNumber, this.message);
  }
}
const sendMessage = async () => {
  await bridge.sendSMS(phone, messageText);
};
exitApp() Android Only

Closes the app. Only supported on Android.

Example
const userConfirmedExit = true; // Connect to your custom modal/dialog state

if (userConfirmedExit) {
  await bridge.exitApp();
}
methods: {
  async confirmExit() {
    const userConfirmedExit = this.showExitDialog
      ? await this.showExitDialog()
      : true;
    if (userConfirmedExit) {
      await bridge.exitApp();
    }
  }
}
const handleExit = async () => {
  const shouldExit = await openExitModal();
  if (shouldExit) {
    await bridge.exitApp();
  }
};

Utilities

Nativify.haptic(type)

Triggers haptic feedback. Unsupported or invalid types degrade to vibration automatically.

Parameters
  • type string
    light, medium, heavy, selection, success, warning, error
Example
await Nativify.haptic('success');
methods: {
  async notifyVibrate() {
    await Nativify.haptic('warning');
  }
}
const handleClick = async () => {
  await Nativify.haptic('selection');
};
Nativify.openOutLink(url)

Opens URL in external browser.

Parameters
  • url string
    URL to open
Example
await Nativify.openOutLink('https://google.com');
methods: {
  async openExternal(url) {
    await Nativify.openOutLink(url);
  }
}
const openLink = async (url) => {
  await Nativify.openOutLink(url);
};
goBack()

Navigate back in webview history.

Example
await bridge.goBack();
methods: {
  async navigateBack() {
    await bridge.goBack();
  }
}
const goBackPage = async () => {
  await bridge.goBack();
};

Widgets Android Only

updateWidget(data)

Updates home screen widget content.

Parameters
  • data object
    Widget display data
Example
await bridge.updateWidget({ count: 42, status: 'active' });
methods: {
  async refreshWidget() {
    await bridge.updateWidget(this.widgetData);
  }
}
const updateHomeWidget = async (data) => {
  await bridge.updateWidget(data);
};

Configuration

isAvailable()

Checks if the native bridge is available (running in the native app container).

Returns
boolean - Bridge availability
Example
if (bridge.isAvailable()) {
  console.log('Running in native app');
} else {
  console.log('Running in browser');
}
mounted() {
  this.isNative = bridge.isAvailable();
  if (this.isNative) {
    console.log('Native features available');
  }
}
useEffect(() => {
  const isNative = bridge.isAvailable();
  setIsNative(isNative);
}, []);

Android Back Button HandlerNEW

window.onBackButton()

Handle Android back button press in your web app. Return true to indicate the event was handled, or false to let the app perform default action (go back or exit).

Return Value
  • true
    Web app handled the back button event
  • false or undefined
    App performs default action (go back or exit)
Default Behavior

If web app doesn't handle the event (300ms timeout):

  • 1. If WebView has history → Navigate back
  • 2. If no history → Exit app
Example - SPA Routing
const router = {
  history: ['home'],
  
  back() {
    if (this.history.length > 1) {
      this.history.pop();
      const previousPage = this.history[this.history.length - 1];
      this.render(previousPage);
      return true;  // Handled
    }
    return false;  // Not handled, exit app
  }
};

window.onBackButton = () => router.back();
// In Vue Router
export default {
  mounted() {
    window.onBackButton = () => {
      if (this.$router.history.length > 1) {
        this.$router.back();
        return true;
      }
      return false;
    };
  }
}
// In React Router
import { useNavigate } from 'react-router-dom';

function App() {
  const navigate = useNavigate();
  
  useEffect(() => {
    window.onBackButton = () => {
      if (window.history.length > 1) {
        navigate(-1);
        return true;
      }
      return false;
    };
  }, [navigate]);
}
Example - Close Modal
window.onBackButton = function() {
  const modal = document.querySelector('.modal.active');
  
  if (modal) {
    closeModal(modal);
    return true;  // Modal closed, event handled
  }
  
  return false;  // No modal open, perform default action
};

Haptics & Vibration

haptic(type)

Provides 7 precise haptic feedback types: light, medium, heavy, selection, success, warning, error.

Example
await bridge.haptic('success');
await bridge.haptic('error');
vibrate(milliseconds)

Triggers device motor vibration for specified duration in ms.

await bridge.vibrate(200);

Biometrics (Fingerprint / Face ID)

canAuthenticate()

Checks if device supports and has registered biometric auth.

const res = await bridge.canAuthenticate();
console.log(res.available); // true / false
authenticate({ reason })

Performs native Fingerprint or Face ID authentication popup.

const result = await bridge.authenticate({ reason: "Verify login" });
if (result.authenticated) { /* success */ }

Phone & SMS

makePhoneCall(phoneNumber)

Initiates native phone call dialer with phone number.

await bridge.makePhoneCall('010-0000-0000');
sendSMS(phoneNumber, message)

Opens SMS compose app with recipient and prefilled message.

await bridge.sendSMS('010-0000-0000', 'Hello from WebBridge');

QR Scanner & NFC

scanQRCode()

Opens real-time high speed camera scanner for QR and barcodes.

const res = await bridge.scanQRCode();
console.log(`Scanned: ${res.code}`);
readNFCTag()

Reads NDEF / RAW tag data from NFC cards tapped on device back.

const nfc = await bridge.readNFCTag();
console.log(nfc.records);

Share & In-App Review

share({ title, text, url })

Opens system native social share sheet.

await bridge.share({ title: 'Nativify', text: 'Convert web to native app', url: 'https://nativify.site' });
requestReview()

Triggers native App Store / Google Play in-app rating popup without leaving app.

await bridge.requestReview();