How does uniapp implementation use JSBridge to interact with native
uniapp implements how to use JSBridge to interact with native, requiring specific code examples
1. Background introduction
In mobile application development, sometimes it is necessary Interact with the native environment, such as calling some native functions or obtaining some native data. As a cross-platform mobile application development framework, uniapp provides a convenient way to interact with native devices, using JSBridge to communicate.
JSBridge is a technical solution for the front-end to interact with the mobile native end. By implementing a bridge on the front-end and the native end respectively, the front-end can call native methods and obtain native data. At the same time, the native end can also pass The bridge sends messages to the front end.
2. JSBridge implementation steps
- Create a new js file in the uniapp project and name it JSBridge.js. This file will serve as a bridge between the front-end and native interactions.
- Define a global object in the JSBridge.js file to store messages and callback functions between the front end and native. The sample code is as follows:
// JSBridge.js let messageHandlers = {}; // 存储前端和原生之间的消息和回调函数 // 注册消息处理函数,前端通过调用此函数来注册对应的回调函数 function registerHandler(name, handler) { messageHandlers[name] = handler; } // 发送消息到原生 function sendMessageToNative(name, data, callback) { let message = { name: name, data: data }; // 注册回调函数 if (callback) { let callbackId = 'cb_' + Date.now(); message.callbackId = callbackId; messageHandlers[callbackId] = callback; } // 向原生发送消息 window.webkit.messageHandlers[name].postMessage(message); } // 处理原生发送过来的消息 function handleMessageFromNative(message) { let handler = messageHandlers[message.name]; if (handler) { handler(message.data, function(response) { sendMessageToNative(message.callbackId, response); // 发送回调消息给原生 }); } } window.messageHandlers = messageHandlers; window.registerHandler = registerHandler; window.sendMessageToNative = sendMessageToNative; window.handleMessageFromNative = handleMessageFromNative;
- Introduce JSBridge.js into the
main.js
file in the uniapp project and register the message processing function. The sample code is as follows:
// main.js import JSBridge from './JSBridge.js'; // 注册消息处理函数,前端通过调用此函数来注册对应的回调函数 JSBridge.registerHandler('getUserInfo', function(data, callback) { console.log('前端收到getUserInfo消息:', data); // 假设需要获取用户信息,可以通过uniapp的API来实现 let userInfo = uni.getUserInfo(); // 返回获取到的用户信息给原生 callback(userInfo); }); // 假设页面上有一个按钮,点击按钮时调用原生的方法 document.getElementById('btn').addEventListener('click', function() { // 发送消息到原生 JSBridge.sendMessageToNative('showAlert', { title: 'Hello', message: 'World' }); });
- Implement the functions and logic of interacting with the front-end in the native environment. The sample code is as follows:
// 在iOS原生代码中 import WebKit class ViewController: UIViewController { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() // 创建WebView webView = WKWebView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)) view.addSubview(webView) // 加载uniapp的HTML文件 if let url = Bundle.main.url(forResource: "uniapp", withExtension: "html") { webView.loadFileURL(url, allowingReadAccessTo: url) } // 注册JSBridge处理函数,用于处理前端发送来的消息 webView.configuration.userContentController.add(self, name: "getUserInfo") webView.configuration.userContentController.add(self, name: "showAlert") } } extension ViewController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if let body = message.body as? [String: Any] { let name = message.name if name == "getUserInfo" { print("原生收到getUserInfo消息:", body) // TODO: 获取原生的用户信息 // 返回用户信息给前端 let userInfo = [ "name": "John", "age": 20 ] let response = [ "data": userInfo ] let javascript = "window.handleMessageFromNative((response))" webView.evaluateJavaScript(javascript, completionHandler: nil) } else if name == "showAlert" { print("原生收到showAlert消息:", body) // 假设实现一个弹窗功能 let title = body["title"] as? String ?? "" let message = body["message"] as? String ?? "" let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } } } }
3. Use JSBridge for front-end and native interaction
Through the above steps, we have implemented the basic JSBridge bridge and message processing functions. In the front-end code, we can call the JSBridge.sendMessageToNative()
method to send messages to the native, and we can also register the corresponding message processing function, such as JSBridge.registerHandler()
in the example . In the native code, we register the processing function through the userContentController.add()
method to receive the messages sent by the front end and implement the corresponding functions.
In the page, when the button is clicked, call the JSBridge.sendMessageToNative('showAlert', { title: 'Hello', message: 'World' })
method to send the message to the native, After receiving the message natively, a pop-up window with title and content will pop up. In addition, when the front end needs to obtain user information, call the JSBridge.sendMessageToNative('getUserInfo')
method to send a message to the native. After the native returns the user information, the front end obtains the data through the callback function and processes it.
To sum up, using JSBridge can easily realize the interaction between uniapp and the native environment, and can implement its own functions and logic in the front end and native respectively. By registering message processing functions, messages can be delivered and processed flexibly.
The above is a brief introduction and code examples about uniapp using JSBridge to realize native interaction. I hope it will be helpful to you.
The above is the detailed content of How does uniapp implementation use JSBridge to interact with native. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Steps to launch UniApp project preview in WebStorm: Install UniApp Development Tools plugin Connect to device settings WebSocket launch preview

Generally speaking, uni-app is better when complex native functions are needed; MUI is better when simple or highly customized interfaces are needed. In addition, uni-app has: 1. Vue.js/JavaScript support; 2. Rich native components/API; 3. Good ecosystem. The disadvantages are: 1. Performance issues; 2. Difficulty in customizing the interface. MUI has: 1. Material Design support; 2. High flexibility; 3. Extensive component/theme library. The disadvantages are: 1. CSS dependency; 2. Does not provide native components; 3. Small ecosystem.

In the win11 system, we can enable multiple monitors to use the same system and operate together by turning on split-screen interaction. However, many friends do not know how to turn on split-screen interaction. In fact, just find the monitor in the system settings. The following is Get up and study. How to open split-screen interaction in win11 1. Click on the Start menu and find "Settings" 2. Then find the "System" settings there. 3. After entering the system settings, select "Display" on the left. 4. Then select "Extend these displays" in the multi-monitor on the right.

UniApp has many conveniences as a cross-platform development framework, but its shortcomings are also obvious: performance is limited by the hybrid development mode, resulting in poor opening speed, page rendering, and interactive response. The ecosystem is imperfect and there are few components and libraries in specific fields, which limits creativity and the realization of complex functions. Compatibility issues on different platforms are prone to style differences and inconsistent API support. The security mechanism of WebView is different from native applications, which may reduce application security. Application releases and updates that support multiple platforms at the same time require multiple compilations and packages, increasing development and maintenance costs.

uniapp development requires the following foundations: front-end technology (HTML, CSS, JavaScript) mobile development knowledge (iOS and Android platforms) Node.js other foundations (version control tools, IDE, mobile development simulator or real machine debugging experience)

When choosing between UniApp and native development, you should consider development cost, performance, user experience, and flexibility. The advantages of UniApp are cross-platform development, rapid iteration, easy learning and built-in plug-ins, while native development is superior in performance, stability, native experience and scalability. Weigh the pros and cons based on specific project needs. UniApp is suitable for beginners, and native development is suitable for complex applications that pursue high performance and seamless experience.

UniApp is based on Vue.js, and Flutter is based on Dart. Both support cross-platform development. UniApp provides rich components and easy development, but its performance is limited by WebView; Flutter uses a native rendering engine, which has excellent performance but is more difficult to develop. UniApp has an active Chinese community, and Flutter has a large and global community. UniApp is suitable for scenarios with rapid development and low performance requirements; Flutter is suitable for complex applications with high customization and high performance.
