How does uniapp implementation use JSBridge to interact with native
Oct 20, 2023 am 08:44 AMuniapp 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 = {}; // 存儲(chǔ)前端和原生之間的消息和回調(diào)函數(shù) // 注冊(cè)消息處理函數(shù),前端通過(guò)調(diào)用此函數(shù)來(lái)注冊(cè)對(duì)應(yīng)的回調(diào)函數(shù) function registerHandler(name, handler) { messageHandlers[name] = handler; } // 發(fā)送消息到原生 function sendMessageToNative(name, data, callback) { let message = { name: name, data: data }; // 注冊(cè)回調(diào)函數(shù) if (callback) { let callbackId = 'cb_' + Date.now(); message.callbackId = callbackId; messageHandlers[callbackId] = callback; } // 向原生發(fā)送消息 window.webkit.messageHandlers[name].postMessage(message); } // 處理原生發(fā)送過(guò)來(lái)的消息 function handleMessageFromNative(message) { let handler = messageHandlers[message.name]; if (handler) { handler(message.data, function(response) { sendMessageToNative(message.callbackId, response); // 發(fā)送回調(diào)消息給原生 }); } } 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'; // 注冊(cè)消息處理函數(shù),前端通過(guò)調(diào)用此函數(shù)來(lái)注冊(cè)對(duì)應(yīng)的回調(diào)函數(shù) JSBridge.registerHandler('getUserInfo', function(data, callback) { console.log('前端收到getUserInfo消息:', data); // 假設(shè)需要獲取用戶信息,可以通過(guò)uniapp的API來(lái)實(shí)現(xiàn) let userInfo = uni.getUserInfo(); // 返回獲取到的用戶信息給原生 callback(userInfo); }); // 假設(shè)頁(yè)面上有一個(gè)按鈕,點(diǎn)擊按鈕時(shí)調(diào)用原生的方法 document.getElementById('btn').addEventListener('click', function() { // 發(fā)送消息到原生 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() // 創(chuàng)建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) } // 注冊(cè)JSBridge處理函數(shù),用于處理前端發(fā)送來(lái)的消息 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) // 假設(shè)實(shí)現(xiàn)一個(gè)彈窗功能 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

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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 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.

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.

Solve the problem of UniApp error: 'xxx' animation effect cannot be found UniApp is a cross-platform application development framework based on the Vue.js framework, which can be used to develop applications for multiple platforms such as WeChat applets, H5, and App. During the development process, we often use animation effects to improve user experience. However, sometimes you will encounter an error: The 'xxx' animation effect cannot be found. This error will cause the animation to fail to run normally, causing inconvenience to development. This article will introduce several ways to solve this problem.

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.

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.
