开放定制化JSAPI

开发者可以通过JSAPI,将端上的能力开放给小程序或H5微应用

注册JSAPI

开发者需要在bundle.plist文件中注册jsapi,填入export-jsapis字段,key为jsapi名称,value为实现jsapi的类,例如
image.png

Demo

  1. @interface DKTOpenFileJSAPIHandler: NSObject<DTKExternalJSAPIHandlerProtocol>
  2. @end
  3. @implementation DKTOpenFileJSAPIHandler
  4. + (NSArray<NSString *>*)apiNameList {
  5. return @"file.open";
  6. }
  7. - (void)handleRequest:(id<DTKExternalAPIRequest>)request
  8. withContext:(id<DTKExternalJSAPIContext>)context
  9. callback:(DTKExternalAPICallback)callback {
  10. // do something with request and context
  11. NSString *fileId = request.data[@"fileId"];
  12. if (fileId == nil) {
  13. NSError *error = [NSError errorWithDomain:@"domain" errorCode:-11001 userInfo:nil];
  14. callback(error);
  15. } else {
  16. NSDictionary *result = self.openFile(fileId);
  17. callback(result);
  18. }
  19. }
  20. @end

成功时,需要传回NSDictionary,失败时,传NSError对象
注意:无论成功还是失败,都需要调用callback,告知小程序(H5微应用)

前端调用

  1. // JSAPI: exclusiveInvoke
  2. // 入参:
  3. // - api:sdk定义的jsapi,比如 "file.open"
  4. // - params:请求的参数
  5. import exclusiveInvoke from 'gdt-jsapi/exclusiveInvoke';
  6. exclusiveInvoke({
  7. api: 'file.open',
  8. params: {
  9. filePath: 'xxxxx',
  10. toekn: 'xxxxx'
  11. }
  12. })