Home > Article > Web Front-end > 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
// 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;
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' }); });
// 在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!