Skip to content

客户端接入JS-SDK指南

iOS接入

一、js代码注入

objective-c
/**
 js代码注入
 */
- (void)injectJSString {
    NSString *jsString = "var JSBridgeNative = {};JSBridgeNative.invoke = function(p0,p1,p2){window.webkit.messageHandlers.JSBridgeNative.postMessage('JSBridgeNative.invoke('+JSON.stringify(p0)+','+JSON.stringify(p1)+','+JSON.stringify(p2)+');');};"
      WKUserScript* script = [[WKUserScript alloc] initWithSource:jsString injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
    [[(WKWebView*)_webView configuration].userContentController addUserScript:script];
    [[(WKWebView*)_webView configuration].userContentController removeScriptMessageHandlerForName:invocationKey];
    [[(WKWebView*)_webView configuration].userContentController addScriptMessageHandler:self name:invocationKey];
}

二、注册js-oc交互

注:所有的方法名都通过apiName返回去匹配

objective-c
/**
 注册js-oc交互,前端传过来的参数
 apiName: 方法名
 parameters: 参数(JSON对象字符串)
 callBackMethod: callback名字(回传给h5,JSON对象字符串)
 */
- (void)registerZBJTJSBridge {
    zbcore_Weak(self);
    _jsContext[@"invoke"] = ^(JSValue* apiName, JSValue *parameters, JSValue *callBackMethod) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weak_self invokeJSSDKBridgeWithMethod:apiName
                                        parameters:parameters
                                          callback:callBackMethod];
        });
    };
    [_jsContext evaluateScript:@"JSBridgeNative.invoke = invoke"];
}

Android接入

java
JsProxy jsProxy = new JsProxy();
//第二个js对象名固定"JSBridgeNative"
webView.addJavascriptInterface(jsProxy, "JSBridgeNative");

// webView 调用本地方法 在JsProxy里添加
/**
 注册js-oc交互,前端传过来的参数
 methodKey: 方法名
 args: 参数(JSON对象字符串)
 callback: callback名字(回传给h5,JSON对象字符串)
 */
@JavascriptInterface
fun invoke(methodKey: String?, args: String?, callback: String?) {
      
}
java
// callback 回调给webView 
String result = 具体见上面方法返回给webView的参数格式(json格式)
String jsResult = String.format("%1s(JSON.stringify(%2s))", callback, result);
webView.evaluateJavascript(jsResult , new ValueCallback<String>() {
	@Override
	public void onReceiveValue(String s) {
                
	}
});

鸿蒙接入

鸿蒙使用系统Web的javaScriptProxy注入Js

javascript
// 1.创建 JsSdk对象
export class JsSdk {
  webController: WebviewController;
  namespace: string = 'JSBridgeNative'
  methodList: Array<string> = ['invoke']
  modules: Record<string, ESObject> = {}; //注册的js方法列表

  constructor(webController: WebviewController) {
    this.webController = webController;
    this.registerModule();
  }

  /**
   * 注册注入方法
   */
  registerModule() {
    this.modules.xxxx= new Xxx();
  }

  inject() {
    const injectModel: JavaScriptProxy = {
      object: this,
      name: this.namespace,
      methodList: ["invoke"],
      controller: this.webController
    }
    return injectModel;
  }

  /**
   * js调用时在此方法中回调
   * @param methodKey 方法名
   * @param args 参数(JSON对象字符串)
   * @param callback callback名字(回传给h5,JSON对象字符串)
   */
  async invoke(methodKey: string, args: string | Record<string, ESObject>, callBackName: string): Promise<ESObject> {
    // 若无对应方法,则返回失败状态
    if (!this.modules[methodKey]) {
      const result = formatResult<null>(null, JSResultCode.functionNotFound)
      this.invokeCallback(callBackName, result);
    }
    let jsonData: Record<string, ESObject> = {};

    if (args) {
      jsonData = JSON.parse(args as string) as Record<string, ESObject>
      //相应js的处理
      const data: ESObject = await this.modules[methodKey].execute(jsonData);
      this.invokeCallback(callBackName, data);
    }
  }

  /**
   * 执行web端的接受返回值的回调函数
   * @param callBackName
   * @param data
   */
  invokeCallback(callBackName: string, data: ESObject) {
    let para = JSON.stringify(data);
    const method = `window.${callBackName}(${JSON.stringify(para)})`
    this.webController.runJavaScript(method)
  }
}

// 2.在web实例中注入JsSdk
jsSdk: JsSdk = new JsSdk(this.webviewController)
Web({ src: this.mUrl, controller: this.webviewController, renderMode: RenderMode.SYNC_RENDER })
  .javaScriptProxy(this.jsSdk.inject())

方法说明

获取用户信息

方法名:getUserInfo

参数:

参数名称类型是否必填说明
requestNumberN0 - 取缓存数据(默认值)
1 - 从网络获取用户信息

callback返回值:

返回值名称类型说明
codeNumber0 - 失败
1 - 成功
dataloginString0 - 未登录
1 - 已登录
mobileString0 - 未绑定手机号
1 - 已绑定手机号
accountIdString用户 accountId
sessionIdStringsessionId
timestampString用于签名的时间戳
signatureString签名
userJson返回当前用户信息,具体根据各个客户端接口调整

分享弹窗

分享完成后,客户端会将分享结果传递给JS端。

方法名:openAppShareMenu

参数:

参数名称类型是否必填说明
titleStringY分享标题
descStringN分享描述
linkStringN分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrlStringN分享图标
onlyImageShareNumberN是否为图片分享:
1 - 是
0 - 否(默认)

callback返回值:

返回值名称类型说明
codeNumber0 - 失败
1 - 成功
datashareToString1 - 微信
2 - 朋友圈
3 - 钉钉
4 - QQ
5 - 微博
6 - QQ空间
100 - 复制链接

设置分享

设置更新客户端默认分享内容,并且可以监听分享行为

方法名:updateAppShareData

参数:

参数名称类型是否必填说明
titleStringY分享标题
descStringN分享描述
linkStringN分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
imgUrlStringN分享图标
onlyImageShareNumberN是否为图片分享:
1 - 是
0 - 否(默认)
callbackFunctionN监听分享行为,经过原生分享内容后,分享成功或失败后的回调方法名

监听分享行为的 callback 返回值:

返回值名称类型说明
codeNumber0 - 失败
1 - 成功
datashareToString1 - 微信
2 - 朋友圈
3 - 钉钉
4 - QQ
5 - 微博
6 - QQ空间
100 - 复制链接

设置分享的 callback 返回值:

返回值名称类型说明
codeNumber0 - 失败
1 - 成功

获取客户端信息

获取的客户端相关信息

方法名:getAppInfo

参数:

参数名称类型是否必填说明
uuidNumberN0 - timestamp 和 signature 为空
1 - 会回传设备唯一编码

callback返回值:

返回值名称类型说明
codeNumber0 - 失败
1 - 成功
dataappString客户端名称
app_codeString客户端标识code
versionString客户端版本信息,versionCode
versionNameString客户端显示版本信息 versionName
deviceString设备
systemString系统
uuidString设备唯一DeviceId,当uuid = 0,timestamp 和 signature 为空
timestampString用于签名的时间戳
signatureString签名

登录弹窗

该方法会弹出登录页面,进行登录流程,当登录完成之后,客户端会将登录结果传递给JS端。如果已经登录,则直接返回成功。登录成功或已经登录的返回结果内需要包含用户信息。

方法名:login

参数:

参数名称类型是否必填说明
refreshNumberN其他 - 登录后不刷新当前页面(默认)
1 - 登录后刷新当前页面

callback返回值:

返回值名称类型说明
codeNumber0 - 失败
1 - 成功
dataloginString0 - 未登录
1 - 已登录
mobileString0 - 未绑定手机号
1 - 已绑定手机号
accountIdString用户 accountId
sessionIdStringsessionId
timestampString用于签名的时间戳
signatureString签名
userJson返回当前用户信息,具体根据各个客户端接口调整