Direct access to native plugins and platform-specific functionality for enhanced mobile app capabilities.
Load and use native plugins for platform-specific functionality.
/**
* Require native plugin by name
* @param pluginName - Name of the native plugin
* @returns Plugin object with native methods
*/
function requireNativePlugin(pluginName: string): object;Usage Examples:
import uni from "@dcloudio/uni-app-plus";
// Load device information plugin
const device = uni.requireNativePlugin('device');
if (device) {
const deviceInfo = device.getInfo();
console.log('Device UUID:', deviceInfo.uuid);
console.log('Device model:', deviceInfo.model);
}
// Load camera plugin for advanced features
const camera = uni.requireNativePlugin('camera');
if (camera) {
camera.takePhoto({
quality: 0.8,
targetWidth: 800,
targetHeight: 600
}, (result) => {
console.log('Photo taken:', result.imageURI);
});
}
// Load custom native plugin
const customPlugin = uni.requireNativePlugin('com.example.customplugin');
if (customPlugin) {
customPlugin.performCustomAction({
parameter1: 'value1',
parameter2: 123
}, (result) => {
console.log('Custom action result:', result);
});
}
// Load network plugin for advanced networking
const network = uni.requireNativePlugin('network');
if (network) {
network.getConnectionInfo((info) => {
console.log('Connection type:', info.type);
console.log('Connection speed:', info.speed);
});
}
// Error handling for missing plugins
const missingPlugin = uni.requireNativePlugin('nonexistent-plugin');
if (!missingPlugin) {
console.warn('Plugin not available on this platform');
// Fallback to uni-app APIs
uni.getNetworkType({
success: (res) => {
console.log('Network type (fallback):', res.networkType);
}
});
}Manage native subviews (SubNVue) for advanced UI functionality.
/**
* Get SubNVue by ID
* @param id - SubNVue identifier
* @returns SubNVue instance or null
*/
function getSubNVueById(id: string): SubNVue | null;
/**
* Get current SubNVue instance
* @returns Current SubNVue or null
*/
function getCurrentSubNVue(): SubNVue | null;
interface SubNVue {
id: string;
show(options?: ShowOptions): void;
hide(options?: HideOptions): void;
setStyle(styles: SubNVueStyles): void;
postMessage(data: any): void;
onMessage(callback: (data: any) => void): void;
close(): void;
}
interface ShowOptions {
duration?: number;
aniShow?: 'slide-in-right' | 'slide-in-left' | 'slide-in-top' | 'slide-in-bottom' | 'fade-in' | 'zoom-out' | 'zoom-fade-out' | 'pop-in' | 'none';
}
interface HideOptions {
duration?: number;
aniHide?: 'slide-out-right' | 'slide-out-left' | 'slide-out-top' | 'slide-out-bottom' | 'fade-out' | 'zoom-in' | 'zoom-fade-in' | 'pop-out' | 'none';
}
interface SubNVueStyles {
left?: string;
top?: string;
width?: string;
height?: string;
backgroundColor?: string;
opacity?: number;
zindex?: number;
}Usage Examples:
// Get and control a SubNVue
const subNVue = uni.getSubNVueById('floating-window');
if (subNVue) {
// Show SubNVue with animation
subNVue.show({
duration: 300,
aniShow: 'slide-in-right'
});
// Update SubNVue styles
subNVue.setStyle({
top: '100px',
left: '20px',
width: '300px',
height: '200px',
backgroundColor: '#ffffff',
opacity: 0.9
});
// Send data to SubNVue
subNVue.postMessage({
type: 'update',
data: {
title: 'New Title',
content: 'Updated content'
}
});
// Listen for messages from SubNVue
subNVue.onMessage((data) => {
console.log('Message from SubNVue:', data);
if (data.action === 'close') {
subNVue.hide({
duration: 200,
aniHide: 'fade-out'
});
}
});
}
// Get current SubNVue (useful when called from within a SubNVue)
const currentSubNVue = uni.getCurrentSubNVue();
if (currentSubNVue) {
// Send message to parent page
currentSubNVue.postMessage({
action: 'subnvue-ready',
timestamp: Date.now()
});
}
// Create floating video player
const videoPlayer = uni.getSubNVueById('video-player');
if (videoPlayer) {
videoPlayer.setStyle({
top: '50px',
right: '20px',
width: '200px',
height: '150px',
zindex: 999
});
videoPlayer.postMessage({
action: 'play',
src: 'https://example.com/video.mp4'
});
videoPlayer.show({
aniShow: 'zoom-out'
});
}Get information about the native menu button (commonly used in mini-programs).
/**
* Get menu button bounding rectangle
* @returns Menu button position and size information
*/
function getMenuButtonBoundingClientRect(): MenuButtonRect;
interface MenuButtonRect {
width: number;
height: number;
top: number;
right: number;
bottom: number;
left: number;
}Usage Example:
// Get menu button position for custom navigation bar
const menuButton = uni.getMenuButtonBoundingClientRect();
console.log('Menu button info:', menuButton);
// Use menu button info to position custom elements
const navigationBarHeight = menuButton.top + menuButton.height + 8; // Add some padding
const customTitleLeft = menuButton.width + 20; // Position title next to menu button
// Apply to page styles
this.setData({
navigationBarHeight: navigationBarHeight + 'px',
titleMarginLeft: customTitleLeft + 'px'
});Utilities for detecting and handling platform-specific functionality.
// Platform detection using native capabilities
const platformUtils = {
isAndroid: () => {
const system = uni.getSystemInfoSync();
return system.platform === 'android';
},
isIOS: () => {
const system = uni.getSystemInfoSync();
return system.platform === 'ios';
},
getAppVersion: () => {
const system = uni.getSystemInfoSync();
return system.version;
},
hasNativePlugin: (pluginName) => {
try {
const plugin = uni.requireNativePlugin(pluginName);
return !!plugin;
} catch (error) {
return false;
}
}
};Access global variables and restore them when needed.
/**
* Restore global variables (internal utility)
*/
function restoreGlobal(): void;Communication bridge for native events.
/**
* Send native event
* @param event - Event name
* @param data - Event data
*/
function sendNativeEvent(event: string, data: object): void;
/**
* Listen for native events
* @param callback - Event callback function
*/
function onNativeEventReceive(callback: (event: NativeEvent) => void): void;
interface NativeEvent {
type: string;
data: any;
timestamp: number;
}Usage Examples:
// Listen for native events
uni.onNativeEventReceive((event) => {
console.log('Native event received:', event);
switch (event.type) {
case 'deviceOrientationChanged':
handleOrientationChange(event.data);
break;
case 'memoryWarning':
handleMemoryWarning(event.data);
break;
case 'networkStatusChanged':
handleNetworkChange(event.data);
break;
}
});
// Send events to native layer
uni.sendNativeEvent('userAction', {
action: 'buttonClick',
buttonId: 'submit',
timestamp: Date.now()
});
// Track app usage
uni.sendNativeEvent('pageView', {
page: 'home',
duration: 5000,
userId: this.currentUserId
});Create wrapper functions for consistent native plugin usage.
// Native plugin wrapper utility
class NativePluginWrapper {
constructor(pluginName) {
this.plugin = uni.requireNativePlugin(pluginName);
this.available = !!this.plugin;
}
isAvailable() {
return this.available;
}
call(method, params, callback) {
if (!this.available) {
callback && callback({ error: 'Plugin not available' });
return;
}
try {
if (typeof this.plugin[method] === 'function') {
this.plugin[method](params, callback);
} else {
callback && callback({ error: 'Method not found' });
}
} catch (error) {
callback && callback({ error: error.message });
}
}
}
// Usage
const devicePlugin = new NativePluginWrapper('device');
if (devicePlugin.isAvailable()) {
devicePlugin.call('getInfo', {}, (result) => {
if (result.error) {
console.error('Device plugin error:', result.error);
} else {
console.log('Device info:', result);
}
});
}Handle native features that may not be available on all platforms.
// Feature detection and fallback
const nativeFeatures = {
biometricAuth: () => {
const auth = uni.requireNativePlugin('biometric-auth');
if (auth) {
return auth.authenticate;
}
return null; // Fallback to password auth
},
advancedCamera: () => {
const camera = uni.requireNativePlugin('advanced-camera');
if (camera) {
return camera;
}
// Fallback to uni.chooseImage
return {
takePhoto: (options, callback) => {
uni.chooseImage({
count: 1,
sourceType: ['camera'],
success: (res) => callback({ imageURI: res.tempFilePaths[0] }),
fail: (error) => callback({ error })
});
}
};
}
};interface NativePlugin {
[methodName: string]: (...args: any[]) => any;
}
interface PluginCallback {
(result: PluginResult): void;
}
interface PluginResult {
success?: boolean;
data?: any;
error?: string;
code?: number;
}
interface NativePluginInfo {
name: string;
version: string;
platform: 'android' | 'ios' | 'all';
methods: string[];
}