All Products
Search
Document Center

Share

Last Updated: Mar 11, 2021

This feature is only supported in 10.1.60 or later baseline versions. You can implement the sharing feature in the client-side with native code.

onShareAppMessage

Customize the onShareAppMessage function on page to set the information for sharing on this page.

  • By default, Share button shows in the upper-right corner of the menu on each Page. If you rewrite onShareAppMessage function, you only customize the content for sharing.
  • You can click Share button to call this operation.
  • This event needs to return an Object used to customize the content for sharing.

Parameters

Parameter Type Instruction The earliest version
from String Trigger source:
  • button: is triggered when a user clicks the Share button on the page.
  • menu: is triggered when a user clicks the Share button in the upper-right corner of the page.
1.10.0
target Object If the from value is button, target is the button to trigger the sharing feature for this time, otherwise the button will be undefined. 1.10.0
webViewUrl String When the page contains web-view component, the URL of web-view will be returned. 1.6.0

Return value

Name Type Required Description The earliest version
title String Yes Customize the title for sharing. None
desc String No Customize description for sharing: Because the maximum length for text shared in Weibo is 140 characters, you need to enter the description within the limit. None
path String Yes Customize the path of the page for sharing. You can get the custom parameters of path by the onLoad method in the life cycle of the mini program. Follow the transmission rules for http get to transmit parameters. When you implement the scenario for sharing in the client-side, the name of this field is page in native code. None
imageUrl String No Customize the small icon for sharing. This feature supports the network image path, apFilePath, and relative path. 1.4.0
bgImgUrl String No Customize the big image for sharing preview. The recommended image size is 750 x 825. This feature supports the network image path, apFilePath, and relative path. 1.9.0
success Function No Callback after the sharing completes. 1.4.0
fail Function No Callback after the sharing fails. 1.4.0

Sample code

  1. Page({
  2. onShareAppMessage() {
  3. return {
  4. title: 'Applet examples'.
  5. desc: 'The official demo for the mini program, which shows the supported operation capabilities and components.'
  6. path: 'page/component/component-pages/view/view?param=123'
  7. };
  8. },
  9. });

Initiate the sharing feature within the page

Note: This feature is supported on base library version 1.1.0 or later versions.

You can set the attribute open-type="share" for button components. This will trigger the Page.onShareAppMessage() event after a user clicks the button, and then triggers the sharing pane. If this event is not defined on the current page, the click operation will be invalid. Relevant components: button.

App.onShareAppMessage

In App(Object) constructor function, you can set onShareAppMessage for global sharing configuration. When you call the sharing feature, global sharing configuration will be applied if you have not set the page-level sharing configuration.

my.hideShareMenu(Object)

Note: This feature is only supportedin 1.7.0 or later base library versions. You need to perform Compatibility operation for earlier versions.

Hide Share button.

Parameters

Name Type Required Instruction
success Function No The callback function for successful operations.
fail Function No The callback function for failed operations.
complete Function No The callback function for ended operations. The callback function will be executed for both successful and failed operations.

Sample code

  1. my.hideShareMenu();

Implement extensions in the client

Due to the high customization degree of implementing the sharing feature, the sharing feature on the native mini program is not available at the moment. Thus, you need to implement the feature yourself.

Implementation

  1. When you initiate the sharing feature in the mini program, this feature will call JSAPI in shareTinyAppMsg. And this feature will also transmit the parameters of object returned by the onShareAppMessage method in JS to the client-side.
  2. You need to implement the processing of shareTinyAppMsg events by customizing the JavaScript (JS) plug-in in the client-side. For the implementation of the JS plug-in, see Android custom JSAPI and iOS custom JSAPI respectively.

Sample code for Android

Note: By default, the Share button on the option menu in the upper-right corner of the mini program is hidden. You can turn on the configuration container switch to show the button. See Container configuration for more details.
  • Initiate the following sharing example in the mini program code:

    1. Page({
    2. data: {
    3. height: 0,
    4. title: 'Thanks for your experience. \nIf you have any suggestions, please feel free to give your feedback.'
    5. },
    6. onLoad() {
    7. const { windowHeight, windowWidth, pixelRatio } = my.getSystemInfoSync();
    8. this.setData({
    9. height: windowHeight * 750 / windowWidth
    10. })
    11. },
    12. onShareAppMessage() {
    13. return {
    14. title: 'Result page',
    15. desc: 'Result is obtained successfully',
    16. myprop: 'hello', //Custom parameter. If the field in the document does not meet your requirement, you can add the field yourself. The field will be transmitted to the client-side.
    17. path: 'pages/result/result'
    18. }
    19. }
    20. });
  • See the following HTML5 plug-in example in the client-side:

    1. package com.mpaas.demo.nebula;
    2. import com.alibaba.fastjson.JSONObject;
    3. import com.alipay.mobile.antui.dialog.AUNoticeDialog;
    4. import com.alipay.mobile.h5container.api.H5BridgeContext;
    5. import com.alipay.mobile.h5container.api.H5Event;
    6. import com.alipay.mobile.h5container.api.H5EventFilter;
    7. import com.alipay.mobile.h5container.api.H5SimplePlugin;
    8. public class ShareTinyMsgPlugin extends H5SimplePlugin {
    9. private static final String ACTION_SHARE = "shareTinyAppMsg";
    10. @Override
    11. public void onPrepare(H5EventFilter filter) {
    12. super.onPrepare(filter);
    13. filter.addAction(ACTION_SHARE);
    14. }
    15. @Override
    16. public boolean handleEvent(H5Event event, final H5BridgeContext context) {
    17. String action = event.getAction();
    18. if (ACTION_SHARE.equals(action)) {
    19. JSONObject param = event.getParam();
    20. String title = param.getString("title");
    21. String desc = param.getString("desc");
    22. String myprop = param.getString("myprop");
    23. String path = param.getString("page");
    24. String appId = event.getH5page().getParams().getString("appId");
    25. // You can call sharing components here to implement further features
    26. String message = "AppID: " + appId + "\n"
    27. + "title: " + title + "\n"
    28. + "desc: " + desc + "\n"
    29. + "myprop: " + myprop + "\n"
    30. + "path: " + path + "\n";
    31. AUNoticeDialog dialog = new AUNoticeDialog(event.getActivity(),
    32. "Sharing result", message, "Sharing successfully", "Sharing failed");
    33. dialog.setPositiveListener(new AUNoticeDialog.OnClickPositiveListener() {
    34. @Override
    35. public void onClick() {
    36. JSONObject result = new JSONObject();
    37. result.put("success", true);
    38. context.sendBridgeResult(result);
    39. }
    40. });
    41. dialog.setNegativeListener(new AUNoticeDialog.OnClickNegativeListener() {
    42. @Override
    43. public void onClick() {
    44. context.sendError(11, "Sharing failed");
    45. }
    46. });
    47. dialog.show();
    48. //
    49. return true;
    50. }
    51. return false;
    52. }
    53. }

iOS code example

  • By default, the Share button in the upper-right corner of the mini program is hidden. When the container initializes, you can set the following API operations to show the Share button:

    Note: You need to manually import the corresponding header file #import <TinyappService/TASUtils.h>.

    1. - (void)application:(UIApplication *)application afterDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    2. ...
    3. [TASUtils sharedInstance].shoulShowSettingMenu = YES;
    4. ...
    5. }
  • Custom the implementation of shareTinyAppMsg JsApi to accept parameters transmitted from the mini program page:
    shareTinyAppMsg

  • In MPJsApi4ShareTinyAppMsg implementation type, you can get the parameters shared on the mini program page to process business. See the following code example:

    1. #import <NebulaPoseidon/NebulaPoseidon.h>
    2. @interface MPJsApi4ShareTinyAppMsg : PSDJsApiHandler
    3. @end
    4. #import "MPJsApi4ShareTinyAppMsg.h"
    5. #import <MessageUI/MessageUI.h>
    6. @interface MPJsApi4ShareTinyAppMsg()<APSKLaunchpadDelegate>
    7. @property(nonatomic, strong) NSString *shareUrlString;
    8. @end
    9. @implementation MPJsApi4ShareTinyAppMsg
    10. - (void)handler:(NSDictionary *)data context:(PSDContext *)context callback:(PSDJsApiResponseCallbackBlock)callback
    11. {
    12. [super handler:data context:context callback:callback];
    13. NSString * appId = context.currentSession.createParam.expandParams[@"appId"];
    14. NSString * page = data[@"page"]?:@"";
    15. NSString * title = data[@"title"]?:@"";
    16. NSString * desc = data[@"desc"]?:@"";
    17. // Concatenate the content for sharing, and call sharing SDK
    18. self.shareUrlString = [NSString stringWithFormat:@"http://appId=%@&page=%@&title=%@&desc=desc", appId, page, title, desc];
    19. [self openPannel];
    20. }
    21. - (void)openPannel {
    22. NSArray *channelArr = @[kAPSKChannelWeibo, kAPSKChannelWeixin, kAPSKChannelWeixinTimeLine, kAPSKChannelSMS, kAPSKChannelQQ, kAPSKChannelQQZone, kAPSKChannelDingTalkSession, kAPSKChannelALPContact, kAPSKChannelALPTimeLine];
    23. APSKLaunchpad *launchPad = [[APSKLaunchpad alloc] initWithChannels:channelArr sort:NO];
    24. launchPad.tag = 1000;
    25. launchPad.delegate = self;
    26. [launchPad showForView:[[UIApplication sharedApplication] keyWindow] animated:YES];
    27. }
    28. #pragma mark - APSKLaunchpadDelegate
    29. - (void)sharingLaunchpad:(APSKLaunchpad *)launchpad didSelectChannel:(NSString *)channelName {
    30. [self shareWithChannel:channelName tag:launchpad.tag];
    31. [launchpad dismissAnimated:YES];
    32. }
    33. - (void)shareWithChannel:(NSString *)channelName tag:(NSInteger)tag{
    34. APSKMessage *message = [[APSKMessage alloc] init];
    35. message.contentType = @"url";//The types are "text", "image", and "url".
    36. message.content = [NSURL URLWithString:self.shareUrlString];
    37. message.icon = [UIImage imageNamed:@"MPShareKit.bundle/Icon_Laiwang@2x.png"];
    38. message.title = @"Here is the webpage title";
    39. message.desc = @"Here is the description information";
    40. APSKClient *client = [[APSKClient alloc] init];
    41. client.disableToastDisplay = YES;
    42. [client shareMessage:message toChannel:channelName completionBlock:^(NSError *error, NSDictionary *userInfo) {
    43. if(! error) {// Successful
    44. [AUToast presentToastWithin:[[UIApplication sharedApplication] keyWindow]
    45. withIcon:AUToastIconSuccess
    46. text:@"Sharing successfully"
    47. duration:2
    48. logTag:@"demo"];
    49. } else {// Failed
    50. NSString *desc = error.localizedFailureReason.length > 0 ? error.localizedFailureReason : @"Sharing failed";
    51. [AUToast presentToastWithin:[[UIApplication sharedApplication] keyWindow]
    52. withIcon:AUToastIconNone
    53. text:desc
    54. duration:2
    55. logTag:@"demo"];
    56. NSLog(@"error = %@", error);
    57. }
    58. }];
    59. }
    60. @end