uni-app整合JsBridge

发布于 1周前 作者 yuanlaile 来自 Uni-App

uni-app整合JsBridge

JsBridge

1 回复

在uni-app中整合JsBridge,通常是为了实现原生功能与H5页面之间的通信。以下是一个简单的示例,展示了如何在uni-app中整合并使用JsBridge。

1. 原生端(Android/iOS)配置

Android

MainActivity.java中,注册JsBridge:

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;
import cn.weex.jsbridge.JsBridge;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化JsBridge
        JsBridge jsBridge = new JsBridge(this, new JsHandler() {
            @Override
            public void handler(String data, UniJSCallback callback) {
                // 处理来自H5的数据
                if ("nativeMethod".equals(data)) {
                    callback.invoke("Hello from Native!");
                }
            }
        });
        // 注册JsBridge到UniApp
        UniModule.registerComponent("JsBridge", jsBridge);
    }
}

iOS

AppController.m中,注册JsBridge(假设使用WebViewJavascriptBridge):

#import "AppController.h"
#import <WebViewJavascriptBridge/WebViewJavascriptBridge.h>

@interface AppController () <UIWebViewDelegate>
@property (nonatomic, strong) WebViewJavascriptBridge *bridge;
@end

@implementation AppController

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // ...
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    [self.window addSubview:webView];
    self.bridge = [WebViewJavascriptBridge bridgeForWebView:webView handler:^(id data, WVJBResponseCallback responseCallback) {
        if ([data isEqualToString:@"nativeMethod"]) {
            responseCallback(@"Hello from Native!");
        }
    }];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"your_uniapp_url"]]];
    return YES;
}

// ...

@end

2. uni-app端调用

在uni-app的页面中,通过plus.bridge.exec调用原生方法(假设已经封装好相关API):

export default {
    methods: {
        callNativeMethod() {
            if (window.WebViewJavascriptBridge) {
                window.WebViewJavascriptBridge.callHandler('nativeMethod', null, (response) => {
                    console.log('Response from native:', response);
                });
            } else {
                // 备用方案,比如使用plus.bridge(针对5+App)
                plus.bridge.exec("JsBridge", "handler", ["nativeMethod"], (result) => {
                    console.log('Response from native:', result);
                });
            }
        }
    }
}

注意:上述代码为简化示例,实际开发中需要根据具体平台进行调整,并确保JsBridge库正确集成到项目中。同时,plus.bridge.exec的用法可能因uni-app版本和具体需求有所不同。

回到顶部