# Interface Description
# 1. Related Interfaces
The web page loaded by the web-view component can use the interfaces provided by JSSDK 1.4.21 (opens new window) and JSSDK 1.4.21(ESM) (opens new window) to invoke Mini-Program-related capabilities.
The supported interfaces are:
| Interface Name | Description | Minimum Version |
|---|---|---|
| ft.miniProgram.navigateTo | Keep the current page and navigate to a page within the application | 1.0.0 |
| ft.miniProgram.navigateBack | Close the current page and return to the previous page or a multi-level page | 1.0.0 |
| ft.miniProgram.switchTab | Navigate to a tabBar page and close all other non-tabBar pages | 1.0.0 |
| ft.miniProgram.redirectTo | Close the current page and navigate to a page within the application | 1.0.0 |
| ft.miniProgram.reLaunch | Close all pages and open a page within the application | 1.0.0 |
| ft.miniProgram.postMessage | Send a message to the Mini-Program, which triggers the component's message event at specific times (Mini-Program back, component destruction, share) | 1.0.0 |
| ft.miniProgram.getEnv | Get the current environment and JSSDK version number | 1.0.0 |
| ft.miniProgram.close | Close the Mini-Program | 1.0.3 |
| ft.miniProgram.navigateToMiniProgram | Navigate to another Mini-Program | 1.0.4 |
| ft.miniProgram.navigateBackMiniProgram | Return to the previous Mini-Program | 1.0.4 |
| ft.miniProgram.onShow | Register a callback for the Mini-Program onShow event | 1.0.6 |
| ft.miniProgram.onHide | Register a callback for the Mini-Program onHide event | 1.0.8 |
| ft.miniProgram.onUnload | Register a callback for the Mini-Program onUnload event | 1.0.8 |
| ft.miniProgram.onWebviewEvent | Listen for events sent by the Mini-Program; supports binding multiple functions | 1.4.1 |
| ft.miniProgram.offWebviewEvent | Remove listeners for events sent by the Mini-Program; cancels all bindings when no parameters are passed | 1.4.1 |
| ft.miniProgram.sendWebviewEvent | Trigger the bindevent method bound to the webview tag | 1.4.1 |
| ft.downloadFile | Download a file | 1.0.0 |
| ft.getAppletInfo | Return the basic information of the current Mini-Program | 1.0.0 |
| ft.openDocument | Open a file | 1.0.0 |
| ft.chooseImage | Take a photo or select an image from the phone's photo album | 1.0.1 |
| ft.getLocalImgData | Get the base64 encoding of an image | 1.0.9 |
| ft.chooseLocation | Open the map to select a location | 1.0.9 |
| ft.getLocation | Get the current geographic location information | 1.0.9 |
| ft.getStorage | Get local cache data | 1.0.9 |
| ft.setStorage | Set local cache data | 1.0.9 |
| ft.removeStorage | Remove local cache data | 1.0.9 |
| ft.clearStorage | Clear local data cache | 1.0.9 |
| ft.getStorageInfo | Get local cache information | 1.0.9 |
| ft.canGoBack | Whether the current H5 page can go back to the previous page | 1.2.0 |
| ft.canNavigateBack | Whether the current Mini-Program page can go back to the previous page | 1.2.0 |
| ft.setNavigationBarTitle | Set the title of the current Mini-Program page | 1.2.0 |
| ft.request | Initiate a network request | 1.3.9 |
| ft.callNativeAPI | H5 calls a native method | 1.4.1 |
| ft.registNativeAPIHandler | Register an H5 method for native invocation (not recommended) | Supported since 1.4.1; this method can only register one callback and cannot be cancelled. It is recommended to use onNativeAPIHandler and offNativeAPIHandler |
| ft.complete | Send a load completion event to the Mini-Program | 1.4.11 |
| ft.onNativeAPIHandler | Register an H5 method for native invocation | 1.4.20 |
| ft.offNativeAPIHandler | Unregister a method | 1.4.20 |
# API Parameter Description
# Callback Function Parameter Description
Most APIs are asynchronous APIs. When calling them, you need to pass in the success, fail, and complete callback functions.
The parameters of the callback functions will uniformly include an errMsg field, indicating the call result. For example:
On a successful call, the success and complete callbacks will be called in sequence, with the return value being
{
errMsg: 'invokeMiniProgramAPI:ok'
}
On a failed call, the fail and complete callbacks will be called in sequence, with the return value being
{
errMsg: 'invokeMiniProgramAPI:fail'
}
Unless otherwise specified, API callbacks are returned in this format. Some API return values will include other data; please refer to the API parameter documentation below.
# API Parameter Documentation
ft.miniProgram.navigateTo(object)
Keep the current page and navigate to a page within the application. You can return to the original page via navigateBack.
- object parameters:
url: String - Required parameter, the path of the page within the application to navigate tosuccess: Function - Callback function for a successful API callfail: Function - Callback function for a failed API callcomplete: Function - Callback function for the end of the API call
ft.miniProgram.navigateBack(object)
Close the current page and return to the previous page or a multi-level page. You can specify the number of levels to go back.
- object parameters:
delta: Number - Optional, the number of pages to go back. If delta is greater than the number of existing pages, it returns to the home page. The default value is 1success: Function - Callback function for a successful API callfail: Function - Callback function for a failed API callcomplete: Function - Callback function for the end of the API call
ft.miniProgram.switchTab(object)
Navigate to a tabBar page and close all other non-tabBar pages. It can only navigate to a tabBar page.
- object parameters:
url: String - Required parameter, the path of the tabBar page to navigate tosuccess: Function - Callback function for a successful API callfail: Function - Callback function for a failed API callcomplete: Function - Callback function for the end of the API call
ft.miniProgram.redirectTo(object)
Close the current page and navigate to a page within the application. The history of the current page will not be retained.
- object parameters:
url: String - Required parameter, the path of the page within the application to navigate tosuccess: Function - Callback function for a successful API callfail: Function - Callback function for a failed API callcomplete: Function - Callback function for the end of the API call
ft.miniProgram.reLaunch(object)
Close all pages and open a page within the application. All page stacks will be cleared.
- object parameters:
url: String - Required parameter, the path of the page within the application to navigate tosuccess: Function - Callback function for a successful API callfail: Function - Callback function for a failed API callcomplete: Function - Callback function for the end of the API call
ft.miniProgram.postMessage(object)
Send a message to the Mini-Program, which triggers the component's message event at specific times (Mini-Program back, component destruction, share).
The function parameter is of Object type, for example:
ft.miniProgram.postMessage({
someKey: 'foo'
})
ft.miniProgram.postMessage({
otherKey: 'boo'
})
ft.miniProgram.getEnv(callback)
Get the current environment and JSSDK version number, used to determine whether the current runtime environment is a Mini-Program.
Parameters:
callback: Function - Callback function that receives the result
Return values:
env: String - Environment type. When opened in a Mini-Program, the value is the string 'miniprogram'; in a non-Mini-Program environment, the value is an empty objectversion: String - JSSDK version numbererrMsg: String - Call result
ft.miniProgram.close()
Close the current Mini-Program.
ft.miniProgram.navigateToMiniProgram(object)
Navigate from the current Mini-Program to another Mini-Program. You can specify the page to navigate to and pass data.
- object parameters:
appId: String - Required parameter, the appId of the Mini-Program to navigate topath: String - Optional, the path of the page to open. If empty, the home page is openedextraData: Object - Optional, the data to pass to the target Mini-Programsuccess: Function - Callback function for a successful API callfail: Function - Callback function for a failed API callcomplete: Function - Callback function for the end of the API call
ft.miniProgram.navigateBackMiniProgram(object)
Return to the previous Mini-Program. You can pass data back to the previous Mini-Program.
- object parameters:
extraData: Object - Optional, the data to return to the previous Mini-Programsuccess: Function - Callback function for a successful API callfail: Function - Callback function for a failed API callcomplete: Function - Callback function for the end of the API call
For example, when navigating from Mini-Program A to Mini-Program B, after B returns to A via navigateBackMiniProgram, if the extraData parameter is carried,
A can obtain the navigation parameters carried by Mini-Program B via the wx.getEnterOptionsSync API
const data = wx.getEnterOptionsSync()
console.log(data)
Or obtain them in the onShow lifecycle of the Mini-Program App
App({
onShow(data) {
console.log(data)
}
})
ft.miniProgram.onShow(callback)
Listen for the Mini-Program show event, which is triggered when the Mini-Program enters the foreground from the background.
- Parameters:
callback: Function - Callback function when the Mini-Program is shown. The callback parameter contains a data field indicating the current Mini-Program route query
ft.miniProgram.onHide(callback)
Listen for the Mini-Program hide event, which is triggered when the Mini-Program enters the background from the foreground.
- Parameters:
callback: Function - Callback function when the Mini-Program is hidden
ft.miniProgram.onUnload(callback)
Listen for the Mini-Program page close event, which is triggered when the Mini-Program page is closed.
- Parameters:
callback: Function - Callback function when the Mini-Program is closed
ft.miniProgram.onWebviewEvent(callback)
Listen for events sent by the Mini-Program, which is triggered when the Mini-Program sends an event via sendWebviewEvent.
- Parameters:
callback: Function - Callback function that receives Mini-Program events
ft.miniProgram.offWebviewEvent(callback)
Remove listeners for events sent by the Mini-Program, cancelling the event listeners previously registered via onWebviewEvent.
- Parameters:
callback: Function - The event callback function to be removed
ft.miniProgram.sendWebviewEvent(object)
Trigger the bindevent method bound to the webview tag, sending data from the H5 page to the Mini-Program.
The function parameter is of Object type, for example:
ft.miniProgram.sendWebviewEvent({
someKey: 'foo'
})
ft.miniProgram.sendWebviewEvent({
otherKey: 'boo'
})
ft.downloadFile(object)
Downloads a file resource to the local device. You can specify the download path and request parameters.
object parameters:
url: String - The URL of the resource to downloadheader: Object - The HTTP request headertimeout: Number - The timeout duration in millisecondsfilePath: String - The path where the file will be stored after downloadsuccess: Function - The callback function for a successful API callfail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Return values:
tempFilePath: String - The temporary file path (local path). Returned when no filePath is passed to specify the file storage path; the downloaded file will be stored in a temporary filefilePath: String - The local path of the downloaded file, consistent with the passed-in filePatherrMsg: String - The call result
ft.openDocument(object)
Opens a file. Supports opening files in various formats such as doc, xls, ppt, pdf, etc.
- object parameters:
filePath: String - The file pathfileType: String - The file type. Possible values: doc, xls, ppt, pdf, docx, xlsx, pptxsuccess: Function - The callback function for a successful API callfail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
ft.getAppletInfo(object)
Retrieves the basic information of the current Mini-Program, including the Mini-Program's ID, name, icon, description, etc.
object parameters:
success: Function - The callback function for a successful API call, returning the basic information of the Mini-Program, including appId, appTitle, appAvatar, appDescription, appThumbnail, path, userId, etc.fail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Return values:
appId: String - The Mini-Program's IDappTitle: String - The Mini-Program's nameappAvatar: String - The Mini-Program's iconappDescription: String - The Mini-Program's descriptionappThumbnail: String - The Mini-Program's cover imagepath: String - The Mini-Program's pathuserId: String - The Mini-Program's developer IDerrMsg: String - The call result
ft.chooseImage(object)
Selects an image from the album or takes a photo with the camera. You can specify the maximum number of selections, image size, and source type.
object parameters:
count: Number - The maximum number of images that can be selected. Default is 9sizeType: Array - The size of the selected images. Possible values are original (original image) and compressed (compressed image). Both are available by defaultsourceType: Array - The source for selecting images. Possible values are album (album) and camera (camera). Both are available by defaultsuccess: Function - The callback function for a successful API call, returning the list of local file paths of the selected photos, tempFilePathsfail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Return values:
tempFilePaths: Array<string> - The list of local file paths of the selected photoserrMsg: String - The call result
ft.getLocalImgData(object)
Retrieves the base64-encoded data of an image, which can convert a local image into a format that can be used directly in a web page.
object parameters:
path: String - The local path of the imagesuccess: Function - The callback function for a successful API call, returning the base64-encoded image datafail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Return values:
localData: String - The base64-encoded image dataerrMsg: String - The call result
ft.chooseLocation(object)
Opens a map to select a location and returns the location information selected by the user, including latitude, longitude, location name, etc.
object parameters:
latitude: Number - Latitudelongitude: Number - Longitudesuccess: Function - The callback function for a successful API call, returning location information including latitude, longitude, location name, and detailed addressfail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Return values:
longitude: Number - Longitudelatitude: Number - Latitudename: String - The location nameaddress: String - The detailed addresserrMsg: String - The call result
ft.getLocation(object)
Retrieves the current geographic location information. You can specify the coordinate system type, and it returns latitude, longitude, speed, accuracy, and other information.
object parameters:
type: String - The coordinate type. Possible values: wgs84, gcj02. Default value is wgs84success: Function - The callback function for a successful API call, returning location information including latitude, longitude, speed, accuracy, etc.fail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Return values:
longitude: Number - Longitudelatitude: Number - Latitudespeed: Number - Speedaccuracy: Number - The accuracy of the locationerrMsg: String - The call result
ft.getStorage(object)
Asynchronously retrieves the content corresponding to the specified key from the local cache.
object parameters:
key: String - The specified key in the local cachesuccess: Function - The callback function for a successful API call, returning the content corresponding to the keyfail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Return values:
data: Object/String - The content corresponding to the keyerrMsg: String - The call result
ft.setStorage(object)
Asynchronously stores data in the specified key in the local cache.
- object parameters:
key: String - The specified key in the local cachedata: Object/String - The content to be stored. Only supports native JS types, Date, and objects that can be serialized via JSON.stringifysuccess: Function - The callback function for a successful API callfail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
ft.removeStorage(object)
Asynchronously removes the content of the specified key from the local cache.
- object parameters:
key: String - The specified key in the local cachesuccess: Function - The callback function for a successful API callfail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
ft.clearStorage(object)
Clears the local data cache, deleting all stored data.
- object parameters:
success: Function - The callback function for a successful API callfail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
ft.getStorageInfo(object)
Asynchronously retrieves the current storage information, including the used space size, total capacity, and a list of all keys.
object parameters:
success: Function - The callback function for a successful API call, returning information including keys (all keys in the current storage) and currentSize (the currently occupied space size, in KB)fail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Return values:
keys: Array - All keys in the current storagecurrentSize: Number - The currently occupied space size, in KBerrMsg: String - The call result
ft.canGoBack(object)
Checks whether the current H5 page can go back to the previous page, used to determine the navigation history state of the current page.
object parameters:
success: Function - The callback function for a successful API call, returning { canGoBack: true // or false }fail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Return values:
canGoBack: Boolean - Indicates whether it can go back to the previous pageerrMsg: String - The call result
ft.canNavigateBack(object)
Checks whether the current Mini-Program page can go back to the previous page, used to determine the current page stack state of the Mini-Program.
object parameters:
success: Function - The callback function for a successful API call, returning { canNavigateBack: true // or false }fail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Return values:
canNavigateBack: Boolean - Indicates whether it can go back to the previous pageerrMsg: String - The call result
ft.setNavigationBarTitle(object)
Dynamically sets the title of the current Mini-Program page. The title can be dynamically updated based on the page content.
- object parameters:
title: String - The page titlesuccess: Function - The callback function for a successful API callfail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Changes to document.title on the H5 page will override the API setting, with the most recently updated title value taking precedence
ft.request(object)
Initiates a network request to retrieve data from a remote server. Supports various HTTP methods and parameter settings.
object parameters:
url: String - The developer server interface addressdata: Object/String/ArrayBuffer - The request parametersheader: Object - Sets the request header. Referer cannot be set in the headermethod: String - The HTTP request method. Default is GETdataType: String - The format of the returned data. Default is jsonsuccess: Function - The callback function for a successful API callfail: Function - The callback function for a failed API callcomplete: Function - The callback function for when the API call ends
Return values:
data: Object - The data returned by the serverstatusCode: Number - The HTTP status codeheader: Object - The header returned by the servererrMsg: String - The call result
ft.callNativeAPI(name, data, callback)
The H5 page calls native methods, enabling interaction between H5 and the native application, and providing access to native features and capabilities.
- Parameters:
name: String - The API name registered nativelydata: Object - The parameters passed to the native methodcallback: Function - The callback function after the native method execution completes
ft.registNativeAPIHandler(name, callback)
Registers an H5 method for native invocation (not recommended), enabling the native application to send messages to and call H5 methods on the H5 page.
- Parameters:
name: String - The registered method namecallback: Function - The callback function executed when called natively
ft.complete()
Sends a loading complete event to the Mini-Program, notifying the Mini-Program that the H5 page has finished loading. When a Mini-Program is configured with a timeout, the H5 needs to notify that loading is complete; otherwise, the bindtimeout event will be triggered after the timeout period.
timeout is in milliseconds.
<web-view src="" timeout="12000" bindtimeout="timeout" />
ft.onNativeAPIHandler(name, callback)
Registers an H5 method for native invocation, allowing native applications to call methods in the H5 page. Supports registering multiple callback functions.
- Parameters:
name: String - The name of the method to registercallback: Function - The callback function to execute when invoked natively
ft.offNativeAPIHandler(name, callback)
Unregisters an H5 method, removing a callback function previously registered via onNativeAPIHandler.
- Parameters:
name: String - The name of the method to unregistercallback: Function - The callback function to unregister
# Sample Code for Some API Calls
ft.miniProgram.navigateTo({ url: '/path/to/page' })
ft.miniProgram.reLaunch({ url: '/path/to/page' })
ft.miniProgram.postMessage({ data: 'foo' })
ft.miniProgram.postMessage({ data: { foo: 'bar' } })
ft.miniProgram.getEnv(function(res) {
console.log(res.env)
console.log(res.version) // Supported since 1.4.18
}) // miniprogram
// Synchronously determine the current H5 runtime environment
console.log(window.__fcjs_environment) // miniprogram
// Close the Mini-Program
ft.miniProgram.close()
ft.miniProgram.navigateBackMiniProgram({
extraData: {},
success: function(res) {
console.log('navigateBackMiniProgram success callback:')
console.log(res)
}
})
ft.miniProgram.navigateToMiniProgram({
appId: '',
success: function(res) {
console.log('navigateToMiniProgram success callback:')
console.log(res)
}
})
ft.miniProgram.onShow(res => {
console.log(res)
// res.data represents the current Mini-Program route query
})
ft.miniProgram.onHide(res => {
// Do Some Thing
})
ft.miniProgram.onUnload(res => {
// Do Some Thing
})
ft.downloadFile({
url,
header,
timeout,
filePath
})
ft.openDocument({
filePath,
fileType
})
ft.chooseImage({
count: 1, // Default 9
sizeType: ['original', 'compressed'], // Can specify original or compressed images; both are available by default
sourceType: ['album', 'camera'], // Can specify the source as album or camera; both are available by default
success: res => {
console.log(res)
}
})
ft.getAppletInfo({
success: res => {
console.log('getAppletInfo', res)
// {
// appAvatar = "Mini-Program icon URL";
// appDescription = "Mini-Program description";
// appId = "Mini-Program id";
// path = "Mini-Program page path when tapping to share";
// appThumbnail = "Mini-Program cover image path, which may be a network path or local path, with a 5:4 aspect ratio";
// appTitle = "Mini-Program name";
// userId = "Mini-Program developer id";
// }
}
})
ft.chooseImage({
count: 1, // Default 9
sizeType: ['original', 'compressed'], // Can specify original or compressed images; both are available by default
sourceType: ['album', 'camera'], // Can specify the source as album or camera; both are available by default
success: res => {
console.log(res)
window.ft.miniProgram.getLocalImgData({
path: res.tempFilePaths[0],
success: res => {
console.log(res)
}
})
}
})
// Get whether the current H5 page can go back to the previous page
ft.canGoBack({
success: function(res) {
console.log(res)
}
})
// Get whether the Mini-Program can go back to the previous page
ft.canNavigateBack({
success: function(res) {
console.log(res)
}
})
// Set the Mini-Program page title
ft.setNavigationBarTitle({
title: 'page title'
})
ft.request({
url: 'https://some.url',
method: 'GET',
data: {
param1: 'test'
},
success: function(res) {
console.log('success', res)
},
fail: function(res) {
console.log('fail', res)
},
complete: function(res) {
console.log('complete', res)
}
})
# 2. Exclusive Interfaces
| Interface Name | Description | Minimum Version |
|---|---|---|
| ft.miniProgram.onWebviewEvent | Listen for events sent by the Mini-Program | 1.4.1 |
| ft.miniProgram.offWebviewEvent | Remove the listener for events sent by the Mini-Program | 1.4.1 |
| ft.miniProgram.sendWebviewEvent | Trigger the bindevent method bound to the webview tag | 1.4.1 |
| ft.callNativeAPI | H5 page calls native API | 1.4.1 |
| ft.onNativeAPIHandler | Register an API in H5 for native invocation | 1.4.20 |
| ft.offNativeAPIHandler | Unregister an API in H5 for native invocation | 1.4.20 |
# 2.1 H5 Page Calls Native API
Example interface name: js2AppFunction
# 2.1.1 iOS Example
[[FATClient sharedClient] fat_registerWebApi:@"js2AppFunction" handler:^(FATAppletInfo *appletInfo, id param, FATExtensionApiCallback callback) {
NSString *name = param[@"name"];
// id params = param[@"data"];
if ([name isEqualToString:@"getLocation"]) {
// Execute location logic
// Return the result to HTML
NSDictionary *dict = @{@"errno":@"403", @"errmsg":@"No permission", @"result": @{@"address":@"Aerospace Science and Technology Plaza, Nanshan District, Shenzhen, Guangdong Province"}};
callback(FATExtensionCodeSuccess, dict);
} else if ([name isEqualToString:@"getColor"]) {
// Execute other logic
// Return the result to HTML
NSDictionary *dict = @{@"r":@"110",@"g":@"150",@"b":@"150"};
callback(FATExtensionCodeSuccess, dict);
}
}];
# 2.1.2 Android Example
API Example
public class WebApi extends BaseApi {
public WebApi(Context context) {
super(context);
}
@Override
public String[] apis() {
return new String[]{"js2AppFunction"}; // API name
}
@Override
public void invoke(String event, JSONObject param, ICallback callback) {
// The corresponding native operation when the method is called
}
}
Kotlin
FinAppClient.extensionWebApiManager.registerApi(WebApi(this))
Java
FinAppClient.INSTANCE.getExtensionWebApiManager().registerApi(new WebApi(this));
# 2.1.3 HarmonyOS Example
API Example
const client = FinAppClient.init(
finAppConfig, // For parameter definitions, refer to the HarmonyOS SDK initialization documentation
context,
entryInfo,
startMode
)
client.registerCustomApi('js2AppFunction', (args: IApiManager.IInvokeArgs) => {
const params = args.params
const callback = args.callback
console.log('customApi params', JSON.stringify(params))
callback.onSuccess({ data: 'customApi success' })
})
# 2.1.4 HTML Example
By referencing our bridge JSSDK file within HTML, you can call the methods registered above.
Example of calling a registered method within HTML:
// Full parameter description
// name: The API name registered natively
// data: The parameters passed to the native method
// callback: The callback function after the native method execution completes
ft.callNativeAPI('js2AppFunction', { name: 'getLocation' }, result => {
console.log(result)
})
# 2.2 Native Calling Methods in HTML
Example interface name: app2jsFunction
# 2.2.1 API in iOS
The native side calls the following API to invoke JS functions in HTML:
NSString *jsonParams = @""; //This should be the JSON string converted from the parameter dictionary.
NSNumber *pageId = @(1234); //This is the pageId passed from HTML
[[FATClient sharedClient] fat_callWebApi:@"app2jsFunction" paramString:jsonParams pageId:pageId handler:^(id result, NSError *error) {
}];
# 2.2.2 API in Android
/**
* Native calls JS function
*
* @param appId Mini-Program id
* @param funcName JS function name
* @param funcParams JS function parameters
* @param webViewId WebView id
* @param callback Callback
*/
fun callJS(appId: String, funcName: String?, funcParams: String?, webViewId: Int, callback: FinCallback<String?>)
Call Example
Kotlin
FinAppClient.appletApiManager.callJS("appId", "app2jsFunction", "funParams", 1, object : FinCallback<String?> {
override fun onSuccess(result: String?) {
Toast.makeText(context, "Call JS succeeded: $result", Toast.LENGTH_SHORT).show()
}
override fun onError(code: Int, error: String) {
Log.d(TAG, "Call JS failed: error code=$code, error message=$error")
}
override fun onProgress(status: Int, info: String) {
Log.d(TAG, "Call JS in progress: status code=$status, info=$info")
}
})
Java
FinAppClient.INSTANCE.getAppletApiManager().callJS("appId", "app2jsFunction", "funParams", 1, new FinCallback<String>() {
@Override
public void onSuccess(String result) {
Toast.makeText(context, "Call JS succeeded: " + result, Toast.LENGTH_SHORT).show();
}
@Override
public void onError(int code, String error) {
Toast.makeText(context, "Call JS failed: error code=" + code + ", error message=" + error, Toast.LENGTH_SHORT).show();
}
@Override
public void onProgress(int status, String info) {
Log.d(TAG, "Call JS in progress: status code=" + status + ", info=" + info);
}
});
# 2.2.3 API in HTML
Similarly, reference the bridge JSSDK file in HTML, then register a method in HTML, for example, named app2jsFunction.
// Full parameter description
// name: The registered method name
// callback: The callback function executed when called natively, receiving parameters passed from native
const callback = function(res) {
// app2jsFunction callback
// res contains data passed from native
console.log(res)
return { success: true } // Can return data to native
}
// Add listener
ft.onNativeAPIHandler('app2jsFunction', callback)
// Remove listener
ft.offNativeAPIHandler('app2jsFunction', callback)
# 2.3 H5 Page Sending Events to Mini-Program
# 2.3.1 H5 Code Example
// H5 page
// Input parameter object
// Data will be passed through to the Mini-Program's bindevent callback function's e.detail.data
ft.miniProgram.sendWebviewEvent({
test: 123
})
# 2.3.2 Mini-Program Code Example
Logic Layer
// Mini-Program /pages/index/index.js
Page({
onEvent(e) {
console.log(e.detail.data.test) // 123
}
})
View Layer
<!-- Mini-Program /pages/index/index.fxml -->
<web-view src="https://xxx.xxx" bindevent="onEvent"></web-view>
# 2.4 Mini-Program Sending Events to H5 Page
# 2.4.1 H5 Code Example
// Input parameter is callback: the callback function to receive Mini-Program events, parameter e contains data passed from the Mini-Program
function onEvent(e) {
console.log(e.test) // 123
}
// Register listener
ft.miniProgram.onWebviewEvent(onEvent)
// Remove listener
ft.miniProgram.offWebviewEvent(onEvent)
# 2.4.2 Mini-Program Code Example
// Input parameter object, representing the data to send to the H5 page
ft.sendWebviewEvent({ test: 123 })