文档

分享

更新时间:

此功能仅在 10.1.60 以及以上基线版本中支持,客户端需在原生代码中实现分享功能。

onShareAppMessage

Page 中定义 onShareAppMessage 函数,设置该页面的分享信息。

  • 每个 Page 页面的右上角菜单中默认会显示 分享 按钮,重写了 onShareAppMessage 函数,只是自定义分享内容。

  • 该接口在用户点击 分享 按钮时调用。

  • 此事件需要返回一个 Object,用于自定义分享内容。

入参

参数

类型

说明

最低版本

from

String

触发来源:

  • button:页面页分享按钮触发;

  • menu:右上角分享按钮触发。

1.10.0

target

Object

如果 from 值为 button,则 target 为触发这次分享的 button,否则为 undefined。

1.10.0

webViewUrl

String

页面中包含 web-view 组件时,返回当前 web-view 的 URL。

1.6.0

返回值

名称

类型

必填

描述

最低版本

title

String

自定义分享标题。

desc

String

自定义分享描述:由于分享到微博只支持最大长度 140 个字,因此建议长度不要超过该限制。

path

String

自定义分享页面的路径,path 中的自定义参数可在小程序生命周期的 onLoad 方法中获取(参数传递遵循 http get 的传参规则)。客户端实现分享场景时,该字段在原生代码的名称对应为 page

imageUrl

String

自定义分享小图标元素,支持网络图片路径、apFilePath 路径和相对路径。

1.4.0

bgImgUrl

String

自定义分享预览大图,建议尺寸 750x825,支持网络图片路径、apFilePath 路径和相对路径。

1.9.0

success

Function

分享成功后回调。

1.4.0

fail

Function

分享失败后回调。

1.4.0

代码示例

Page({
  onShareAppMessage() {
    return {
      title: '小程序示例',
      desc: '小程序官方示例 Demo,展示已支持的接口能力及组件。',
      path: 'page/component/component-pages/view/view?param=123'
    };
  },
});

页面内发起分享

说明

基础库版本 1.1.0 开始支持。

通过给 button 组件设置属性 open-type="share",可以在用户点击按钮后触发 Page.onShareAppMessage() 事件,并唤起分享面板,如果当前页面没有定义此事件,则点击后无效果。相关组件:button

App.onShareAppMessage

可以在 App(Object) 构造函数中设置全局的分享 onShareAppMessage 配置,当调用分享时,如果未配置页面级的分享设置则会使用全局的分享设置。

my.hideShareMenu(Object)

说明

基础库版本 1.7.0 开始支持,低版本需做 兼容处理

隐藏分享按钮。

入参

名称

类型

必填

说明

success

Function

调用成功的回调函数。

fail

Function

调用失败的回调函数。

complete

Function

调用结束的回调函数(调用成功、失败都会执行)。

代码示例

my.hideShareMenu();

客户端扩展实现

由于分享的实现自定义程度比较高,因此目前暂不提供原生的小程序分享功能,需要您自己实现。

实现方式

  1. 小程序端发起分享时会调用 shareTinyAppMsg 的 JSAPI,它会将 JS 中 onShareAppMessage 方法返回的对象中的参数透传给客户端。

  2. 客户端侧需实现自定义 JS 插件处理 shareTinyAppMsg 事件。关于 JS 插件如何实现,需分别参考 Android 自定义 JSAPIiOS 自定义 JSAPI

Android 代码示例

说明:小程序右上角选项菜单中的分享按钮默认隐藏,需要通过配置容器开关显示,详情参见 容器配置

  • 在小程序代码中发起分享示例如下:

    Page({
    data: {
      height: 0,
      title: '感谢体验!\n有任何建议欢迎反馈'
    },
    onLoad() {
      const { windowHeight, windowWidth, pixelRatio } = my.getSystemInfoSync();
      this.setData({
        height: windowHeight * 750 / windowWidth
      })
    },
    onShareAppMessage() {
      return {
        title: '结果页',
        desc: '成功获取到结果',
        myprop: 'hello', //自定义参数,如果文档中字段不满足需求,可根据需求增加,会被透传至客户端
        path: 'pages/result/result'
      }
    }
    });
  • 客户端侧 H5 插件代码示例如下:

      package com.mpaas.demo.nebula;
    
      import com.alibaba.fastjson.JSONObject;
      import com.alipay.mobile.antui.dialog.AUNoticeDialog;
      import com.alipay.mobile.h5container.api.H5BridgeContext;
      import com.alipay.mobile.h5container.api.H5Event;
      import com.alipay.mobile.h5container.api.H5EventFilter;
      import com.alipay.mobile.h5container.api.H5SimplePlugin;
    
      public class ShareTinyMsgPlugin extends H5SimplePlugin {
    
          private static final String ACTION_SHARE = "shareTinyAppMsg";
    
          @Override
          public void onPrepare(H5EventFilter filter) {
              super.onPrepare(filter);
              filter.addAction(ACTION_SHARE);
          }
    
          @Override
          public boolean handleEvent(H5Event event, final H5BridgeContext context) {
              String action = event.getAction();
              if (ACTION_SHARE.equals(action)) {
                  JSONObject param = event.getParam();
                  String title = param.getString("title");
                  String desc = param.getString("desc");
                  String myprop = param.getString("myprop");
                  String path = param.getString("page");
                  String appId = event.getH5page().getParams().getString("appId");
    
                  // 此处可调用分享组件,实现后续功能
                  String message = "应用ID: " + appId + "\n"
                          + "title: " + title + "\n"
                          + "desc: " + desc + "\n"
                          + "myprop: " + myprop + "\n"
                          + "path: " + path + "\n";
    
                  AUNoticeDialog dialog = new AUNoticeDialog(event.getActivity(),
                          "分享结果", message, "分享成功", "分享失败");
                  dialog.setPositiveListener(new AUNoticeDialog.OnClickPositiveListener() {
                      @Override
                      public void onClick() {
                          JSONObject result = new JSONObject();
                          result.put("success", true);
                          context.sendBridgeResult(result);
                      }
                  });
                  dialog.setNegativeListener(new AUNoticeDialog.OnClickNegativeListener() {
                      @Override
                      public void onClick() {
                          context.sendError(11, "分享失败");
                      }
                  });
                  dialog.show();
                  //
                  return true;
              }
              return false;
          }
      }

iOS 代码示例

  • 小程序右上角的分享按钮默认为隐藏,您可以在容器初始化时,设置以下接口,以显示分享按钮:

    说明:需手动引入对应头文件 #import <TinyappService/TASUtils.h>

      - (void)application:(UIApplication *)application afterDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
          ...
    
          [TASUtils sharedInstance].shoulShowSettingMenu = YES;
    
          ...
      }
  • 自定义实现 shareTinyAppMsg JsApi,接受小程序页面透传的参数: shareTinyAppMsg

  • MPJsApi4ShareTinyAppMsg 的实现类中,您可以获取到小程序页面分享的参数,进行业务处理。示例代码如下:

      #import <NebulaPoseidon/NebulaPoseidon.h>
      @interface MPJsApi4ShareTinyAppMsg : PSDJsApiHandler
    
      @end
    
      #import "MPJsApi4ShareTinyAppMsg.h"
      #import <MessageUI/MessageUI.h>      
    
      @interface MPJsApi4ShareTinyAppMsg()<APSKLaunchpadDelegate>
    
      @property(nonatomic, strong) NSString *shareUrlString;
    
      @end
    
      @implementation MPJsApi4ShareTinyAppMsg
    
      - (void)handler:(NSDictionary *)data context:(PSDContext *)context callback:(PSDJsApiResponseCallbackBlock)callback
      {
          [super handler:data context:context callback:callback];
    
          NSString * appId = context.currentSession.createParam.expandParams[@"appId"];
          NSString * page = data[@"page"]?:@"";
          NSString * title = data[@"title"]?:@"";
          NSString * desc = data[@"desc"]?:@"";
    
          // 拼接分享的内容,调用分享 SDK
          self.shareUrlString = [NSString stringWithFormat:@"http://appId=%@&page=%@&title=%@&desc=desc", appId, page, title, desc];
          [self openPannel];
      }
    
      - (void)openPannel {
          NSArray *channelArr = @[kAPSKChannelWeibo, kAPSKChannelWeixin, kAPSKChannelWeixinTimeLine, kAPSKChannelSMS, kAPSKChannelQQ, kAPSKChannelQQZone, kAPSKChannelDingTalkSession, kAPSKChannelALPContact, kAPSKChannelALPTimeLine];
          APSKLaunchpad *launchPad = [[APSKLaunchpad alloc] initWithChannels:channelArr sort:NO];
          launchPad.tag = 1000;
          launchPad.delegate = self;
    
          [launchPad showForView:[[UIApplication sharedApplication] keyWindow] animated:YES];
      }
    
      #pragma mark - APSKLaunchpadDelegate
      - (void)sharingLaunchpad:(APSKLaunchpad *)launchpad didSelectChannel:(NSString *)channelName {
          [self shareWithChannel:channelName tag:launchpad.tag];
          [launchpad dismissAnimated:YES];
      }
    
      - (void)shareWithChannel:(NSString *)channelName tag:(NSInteger)tag{
          APSKMessage *message = [[APSKMessage alloc] init];
          message.contentType = @"url";//类型分"text","image", "url"三种
          message.content = [NSURL URLWithString:self.shareUrlString];
          message.icon = [UIImage imageNamed:@"MPShareKit.bundle/Icon_Laiwang@2x.png"];
          message.title = @"这里是网页标题";
          message.desc = @"这里是描述信息";
          APSKClient *client = [[APSKClient alloc] init];
          client.disableToastDisplay = YES;
    
          [client shareMessage:message toChannel:channelName completionBlock:^(NSError *error, NSDictionary *userInfo) {
              if(!error) {// 成功
                  [AUToast presentToastWithin:[[UIApplication sharedApplication] keyWindow]
                                     withIcon:AUToastIconSuccess
                                         text:@"分享成功"
                                     duration:2
                                       logTag:@"demo"];
              } else {// 失败
                  NSString *desc = error.localizedFailureReason.length > 0 ? error.localizedFailureReason : @"分享失败";
                  [AUToast presentToastWithin:[[UIApplication sharedApplication] keyWindow]
                                     withIcon:AUToastIconNone
                                         text:desc
                                     duration:2
                                       logTag:@"demo"];
                  NSLog(@"error = %@", error);
              }
          }];
      }
    
      @end
  • 本页导读 (0)
文档反馈