npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

js-miniapp-sdk

v1.21.0

Published

Mini App SDK for JavaScript

Downloads

46

Readme

Mini App JS SDK

The Mini App SDK for JavaScript can be used to access Android/iOS device and App specific features from a Mini App. It is intended to be used in conjunction with the Android Mini App SDK and iOS Mini App SDK.

JS SDK Developer documentation

Table of Contents

{:.no_toc}

  • Table of contents {:toc}

Getting Started

This SDK can be used either as an NPM module or via the bundled script file.

Usage as NPM module

The SDK package can be installed in your project from the NPM registry:

npm install js-miniapp-sdk

And then it can be used as an import in your project:

import MiniApp from "js-miniapp-sdk";

MiniApp.getMessagingUniqueId()
    .then(id => {
    // ...

Usage via bundled script

You can alternatively use the bundled script file to use the SDK. When using the bundled script file, a global MiniApp object will be available for using the SDK.

First, download the bundled script file from the releases page. You can then include it as a normal <script> tag in your HTML:

<script src="miniapp.bundle.js"></script>

Then you can acces the SDK methods via window.MiniApp.default.

window.MiniApp.default.getMessagingUniqueId()
    .then(id => {
    // ...

Mini App Manifest

There is a manifest for each mini app. The manifest provides the info for Android/iOS SDK to handle the mini app so the mini app developer should understand the structure and data type of manifest.

The manifest contains:

  • Required permissions
  • Optional permissions
  • Access token permissions
  • Custom metadata

Here is the example of manifest. You can also see it in our sample app.

{
  // The mini app should use "reqPermissions" for setting which permissions it requires.
  // These permissions will be requested by the host app before launching and downloading the mini app.
  // The user MUST accept these permissions before the mini app can be launched.
  "reqPermissions": [
    {
      "name": "rakuten.miniapp.user.USER_NAME",
      "reason": "Describe your reason here (optional)."
    },
    {
      "name": "rakuten.miniapp.user.PROFILE_PHOTO",
      "reason": "Describe your reason here (optional)."
    }
  ],
  // The mini app should use "optPermissions" for setting which permissions it will optionally use.
  // These permissions will be requested by the host app before launching and downloading the mini app.
  // The user can choose to either accept or deny these permissions before the mini app is launched.
  "optPermissions": [
    {
      "name": "rakuten.miniapp.user.CONTACT_LIST",
      "reason": "Describe your reason here (optional)."
    },
    {
      "name": "rakuten.miniapp.device.LOCATION",
      "reason": "Describe your reason here (optional)."
    }
  ],
  // For access tokens, can define which "audience" and "scopes" you would like permission to use
  "accessTokenPermissions": [
    {
      "audience": "rae",
      "scopes": ["idinfo_read_openid", "memberinfo_read_point"]
    },
    {
      "audience": "api-c",
      "scopes": ["your_service_scope_here"]
    }
  ],
  // The Host App can require additional keys that the mini app developer must set
  "customMetaData": {
    "exampleKey": "test"
  }
}

Mini App Features

User details

Retrieve a unique ID

  1. getUniqueId() - This method is deprecated from 2.0 and renamed to getMauid()

    API: MiniAppFeatures.getUniqueId

    You can retrieve a unique ID which was generated by the Android or iOS App to represent the user of the mini app:

    import MiniApp from 'js-miniapp-sdk';
    
    MiniApp
      .getUniqueId()
      .then(id => {
        console.log(id);
      })
      .catch(error => {
        console.error(error);
      });
  2. getMauid() - This method is replaced with the getUniqueId()

    API: MiniAppFeatures.getmauid

    You can retrieve a unique ID which was generated by the Android or iOS App to represent the user of the mini app:

    import MiniApp from 'js-miniapp-sdk';
    
    MiniApp
      .getMauid()
      .then(id => {
        console.log(id);
      })
      .catch(error => {
        console.error(error);
      });
  3. getMessagingUniqueId() - This method is used to retrieve a Unqiue ID that can be used for messages.

    API: MiniAppFeatures.getmessaginguniqueid

    import MiniApp from 'js-miniapp-sdk';
    
    MiniApp
      .getMauid()
      .then(id => {
        console.log(id);
      })
      .catch(error => {
        console.error(error);
      });
**API:** [MiniAppFeatures.getphonenumber](api/interfaces/miniappfeatures.md#getphonenumber)

```javascript
import MiniApp from 'js-miniapp-sdk';

MiniApp.user
  .getPhoneNumber()
  .then(number => {
    console.log(number);
  })
  .catch(error => {
    console.error(error);
  });
```

Request Permissions

There must be permission requests from miniapp to access some mobile components and data. Users can revoke a permission at any time, so you must always request the permission every time before you use the associated API. Note that accepted permissions are cached, so if a User has already accepted a permission then they will not be shown the permission dialog again unless they manually revoke the permission.

There are two types of permissions:

  • Custom permissions: Access User data or device features which the Host App controls. Displays Host App's custom permission dialog.
  • Device permissions: Access device features. Displays Android/iOS platform permission dialog.

Mini app developer can define which permissions are required and optional in mini app manifest. You do not need to request permission when declaring them as required type.

Custom Permissions

API: MiniAppFeatures.requestCustomPermissions, CustomPermissionName, CustomPermissionStatus

These permissions are related to accessing the User data or device features which the Host App controls, and the Host App will display a custom permission dialog. Multiple permissions can be requested at once. These permissions should be requested before you attempt to access the User's data or certain device features.

These permissions are requested using the MiniAppFeatures.requestCustomPermissions method.

| Permission Name | Description | | ------------------------------------ | --------------------------------------------------------------- | | CustomPermissionName.USER_NAME | Grant access to the User's name. | | CustomPermissionName.PROFILE_PHOTO | Grant access to the user's Profile Photo. | | CustomPermissionName.CONTACT_LIST | Grant access to the user's contact list. | | CustomPermissionName.ACCESS_TOKEN | Grant access to the a user's access token. | | CustomPermissionName.LOCATION | Grant access to the device's location (custom permission only). | | CustomPermissionName.SEND_MESSAGE | Allow miniapp to send message to specific contact via hostapp. | | CustomPermissionName.POINTS | Allow miniapp to retrieve points. | | CustomPermissionName.FILE_DOWNLOAD | Allow miniapp to download files. |

Usage example
import MiniApp, {
  CustomPermissionResult,
  CustomPermissionName,
} from 'js-miniapp-sdk';

MiniApp
  .requestCustomPermissions([
    {
      name: CustomPermissionName.USER_NAME,
      description: 'This text will be shown to the user.',
    },
    {
      name: CustomPermissionName.PROFILE_PHOTO,
      description: 'This text will be shown to the user.',
    },
    {
      name: CustomPermissionName.CONTACT_LIST,
      description: 'This text will be shown to the user.',
    },
    {
      name: CustomPermissionName.ACCESS_TOKEN,
      description: 'This text will be shown to the user.',
    },
    {
      name: CustomPermissionName.LOCATION,
      description: 'This text will be shown to the user.',
    },
    {
      name: CustomPermissionName.SEND_MESSAGE,
      description: 'This text will be shown to the user.',
    },
    {
      name: CustomPermissionName.POINTS,
      description: 'This text will be shown to the user.',
    },
    {
      name: CustomPermissionName.FILE_DOWNLOAD,
      description: 'This text will be shown to the user.',
    },
  ])
  .then(result => {
    const allowed = result
      .filter(
        permission => permission.status === CustomPermissionResult.ALLOWED
      )
      .map(permission => permisssion.name);

    if (allowed.indexOf(CustomPermissionName.USER_NAME) > -1) {
      // Access and use the User Name data
    }
  })
  .catch(error => {
    console.error(error); // An error occured
  });

Device Permissions

API: MiniAppFeatures.requestLocationPermission

These permissions are for accessing device features, and they will display a platform-specific dialog which is controlled by the Android or iOS operating system. Device permissions can only be requested one at a time.

Each device permission is requested using a specific method for that permission. Device permissions also have an associated Custom permissions, so you should first request the custom permission before requesting the device permission. However, if you did not request the custom permission first, then the method will automatically request the custom permission from the user.

| Permission Method | Description | | ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- | | requestLocationPermission | Grant access to the device location (both device permission & custom permission). |

Usage example
// Location Permission
import MiniApp from 'js-miniapp-sdk';

MiniApp
  .requestLocationPermission('This description will be shown to the user.')
  .then(success => {
    console.log(success); // Allowed.
  })
  .catch(error => {
    console.error(error); // Permission is not granted due to many circumstances.
  });

Show Ads

API: Ad.loadInterstitialAd, Ad.loadRewardedAd, Ad.showInterstitialAd, Ad.showRewardedAd, Reward

Mini App SDK allows you to display ads upon requesting from a Mini App with an ad unit id. This requires you to first load an Ad by passing an ID. You can then display an Ad in the Ad Unit by passing the same ID which was used for loading.

Note that typically you should load your Ads at some point earlier than you intend to use them, such as at App launch time. You can also pre-load multiple Ads by calling MiniApp.loadInterstialAd or MiniApp.loadRewardedAd multiple times.

Currently two ad types are supported,

  1. Interstitial
  2. Rewarded
import MiniApp from 'js-miniapp-sdk';

const adUnitID = 'xxx-xxx-xxxxxxxxxxxxx';

MiniApp
  .loadInterstitialAd(adUnitID)
  .then(response => {
    MiniApp
      .showInterstitialAd(adUnitID)
      .then(response => console.log(response))
      .catch(error => console.error(response));
  })
  .catch(error => console.error(response));
import MiniApp from 'js-miniapp-sdk';

const adUnitID = 'xxx-xxx-xxxxxxxxxxxxx';

MiniApp
  .loadRewardedAd(adUnitID)
  .then(response => {
    MiniApp
      .showRewardedAd(adUnitID)
      .then(response => console.log(response))
      .catch(error => console.error(response));
  })
  .catch(error => console.error(response));

Events

Mini app can listen to the following events that will be sent/triggered by the Hostapp/Native SDKs to Mini app.

Mini App Events

API: MiniAppEvents

These MiniAppEvents events are more live Mini app life cycle events that will be broadcast when a event occurs

  • EXTERNAL_WEBVIEW_CLOSE

  • PAUSE

  • RESUME

    window.addEventListener(MiniAppEvents.EXTERNAL_WEBVIEW_CLOSE, function (e) {
      // To-do
    });

Keyboard events

API: MiniAppKeyboardEvents

These MiniAppKeyboardEvents events will be triggered when a keyboard is shown or dismissed

  • KEYBOARDSHOWN

  • KEYBOARDHIDDEN

    import MiniApp from 'js-miniapp-sdk';
    
    window.addEventListener(MiniAppKeyboardEvents.KEYBOARDSHOWN, function (e) {
      // To-do
    });

Host app events Available from v1.16.0

API: HostAppEvents

These HostAppEvents will be triggered when the host app wants to notify something to the Mini app

  • RECEIVE_JSON_INFO

    import MiniApp from 'js-miniapp-sdk';
    
    window.addEventListener(MiniAppKeyboardEvents.RECEIVE_JSON_INFO, function (e) {
      // To-do
    });

Share Info

API: MiniAppFeatures.shareInfo,

ShareInfoType

It is possible for the mini app user to share data with another App by showing the native content sharing chooser.

The data format must match the ShareInfoType.

import MiniApp from 'js-miniapp-sdk';

const info = { content: inputValue };

MiniApp
  .shareInfo(info)
  .then(success => console.log(success))
  .catch(error => console.error(error));

Requesting User details

API: UserInfoProvider

Please make sure that User have allowed respective custom permission before requesting the user detail.

User name

API: UserInfoProvider.getUserName, CustomPermissionName.USER_NAME

Returns the Username text from the Host app.

import MiniApp from 'js-miniapp-sdk';

MiniApp.user
  .getUserName()
  .then(userName => {
    console.log(userName);
  })
  .catch(error => {
    console.error(error);
  });

Profile Photo

API: UserInfoProvider.getProfilePhoto, CustomPermissionName.PROFILE_PHOTO

Returns the Profile Photo URI from the Host app.

import MiniApp from 'js-miniapp-sdk';

MiniApp.user
  .getProfilePhoto()
  .then(profilePhoto => {
    console.log(profilePhoto);
  })
  .catch(error => {
    console.error(error);
  });

Contact List

API: UserInfoProvider.getContacts, Contact, CustomPermissionName.CONTACT_LIST

Returns the Contact list from the Host app.

import MiniApp from 'js-miniapp-sdk';

MiniApp.user
  .getContacts()
  .then(contacts => {
    console.log(contacts);
  })
  .catch(error => {
    console.error(error);
  });

Access Token

API: UserInfoProvider.getAccessToken, AccessTokenData, AccessTokenScopes, CustomPermissionName.ACCESS_TOKEN

You can get an access token provided by the Host App.

There are 2 reasons your access token request can be rejected:

  • The Host App will be able to deny your request if your mini app ID is not approved to access the token.
  • Your request will also be denied by the MiniApp SDK if your audience and scopes do not match the ones defined in the Mini App Manifest

Returns the AccessTokenData list from the Host app.

AccessTokenData contains token,validUntil and scopes details.

import MiniApp from 'js-miniapp-sdk';

MiniApp.user
  .getAccessToken('TOKEN_AUDIENCE', ['TOKEN_SCOPE1', 'TOKEN_SCOPE2'])
  .then(data => {
    const isValid = data.validUntil.getTime() >= Date.now();
    if (isValid) {
      const token = data.token;
      // Use token
    }
  })
  .catch(error => console.error(error));

Set screen orientation

API: MiniAppFeatures.setScreenOrientation, ScreenOrientation

It is possible to change and lock device screen orientation. However, there is no guarantee that all hostapps and device OS allow the force screen change so MiniApp should not rely on this.

The support screen change cases are defined as ScreenOrientation. After finish locking, the miniapp can release the lock and grant back the normal orientation controller to device. Please use ScreenOrientation.LOCK_RELEASE

import MiniApp from 'js-miniapp-sdk';

MiniApp
  .setScreenOrientation(ScreenOrientation.LOCK_LANDSCAPE) // or LOCK_PORTRAIT, LOCK_RELEASE.
  .then(success => {
    console.log(success);
  })
  .catch(error => {
    console.error(error);
  });

Send message

API: ChatServiceProvider MessageToContact

Send message to the single contact

import MiniApp from 'js-miniapp-sdk';

MiniApp.chatService
  .sendMessageToContact(messageToContact)
  .then(contactId => {
    // contact id string.
    console.log(contactId);
  })
  .catch(error => {
    console.error(error);
  });

Send message by contact id

Please make sure that User have allowed message sending custom permission before sending message to specific contact.

import MiniApp from 'js-miniapp-sdk';

MiniApp.chatService
  .sendMessageToContactId(id, messageToContact)
  .then(contactId => {
    console.log(contactId);
  })
  .catch(error => {
    console.error(error);
  });

Send message to multiple contacts

import MiniApp from 'js-miniapp-sdk';

MiniApp.chatService
  .sendMessageToMultipleContacts(messageToContact)
  .then(contactIds => {
    // contact id string array.
    console.log(contactIds);
  })
  .catch(error => {
    console.error(error);
  });

Open device camera

Please make sure that capture attribute is available, it will open device camera from miniapp.

<html>
  ...
  <div data-role="fieldcontain">
    <label for="name">Open file chooser to select file using camera</label>
    <input id="fileselect" type="file" accept="image/*" capture="environment" />
  </div>
  ...
</html>

Set Close alert Available from v1.15.0

API: MiniApp.miniappUtils.setCloseAlert

import MiniApp from 'js-miniapp-sdk';

const alertInfo: CloseAlertInfo = {
  shouldDisplay: true,
  title: "Info",
  description: "Would you like to close the miniapp?",
};
MiniApp.miniappUtils
  .setCloseAlert(alertInfo)
  .then(() => {
  })
  .catch((error) => {
  });
});

Universal Bridge Available from v1.16.0

API: MiniApp.universalBridge.sendJsonToHostapp

MiniApp users can send any JSON/String from MiniApp to HostApp as well as receive any JSON/String from HostApp to MiniApp.

Send a JSON/String from MiniApp to HostApp

Please use the following example in the MiniApp:

import MiniApp from 'js-miniapp-sdk';

const inputValue = '{"data":"This is a sample json information"}';
const info = { content: inputValue };
MiniApp.universalBridge
  .sendJsonToHostapp(info)
  .then(success => {
    console.log(success);
  })
  .catch(error => {
    console.error(error);
  });

Send a UniversalBridgeInfo from MiniApp to HostApp Available from v1.18.0

Please use the following example in the MiniApp:

import MiniApp from 'js-miniapp-sdk';

const info: UniversalBridgeInfo = {
  key: "launch",
  value: "deeplinkurl",
  description: "Description of the info that is passed",
};

const info = { content: inputValue };

MiniApp.universalBridge
  .sendInfoToHostapp(info)
  .then(success => {
    console.log(success);
  })
  .catch(error => {
    console.error(error);
  });

Receive a JSON/String from HostApp to MiniApp

Please use the following example in the MiniApp:

import HostAppEvents from 'js-miniapp-sdk';

window.addEventListener(HostAppEvents.RECEIVE_JSON_INFO, function(e) {
  let message = e.detail.message;
  console.log(message);
});

Close miniapp Available from v1.16.0

When the miniapp want's to close, they can use this interface to close by itself. Calling this interface, it would let know the host app know that the miniapp wants to close. Host app can decide if it can proceed with the flow.

import MiniApp from 'js-miniapp-sdk';

MiniApp.miniappUtils.closeMiniApp(true).catch((error) => {
});

In-App Purchases

You can perform the in-app purchases for the products available for In-App Purchases associated with Google Play™.

Get all products list

This will retrieve the list of products details available for In-App Purchase associated with Google Play™. This will return only the list of products associated with Mini app in the platform

import MiniApp from 'js-miniapp-sdk';

MiniApp.purchases
      .getAllProducts()
      .then((success) => {
        console.log(success);
      })
      .catch((error) => {
        console.error(error);
      });

Purchase a product with product id

This will request for the In-app Purchase of a product with product id associated with Google Play™. Returns the PurchasedProduct object with transaction details.

import MiniApp from 'js-miniapp-sdk';

MiniApp.purchases
      .purchaseProductWith(productId)
      .then((success) => {
        console.log(success);
      })
      .catch((error) => {
        console.error(error);
      });

Consume a purchase

This will request to Consume the product that is purchased using the purchaseProductWith API Returns the PurchasedProduct object with transaction details.

import MiniApp from 'js-miniapp-sdk';

MiniApp.purchases
      .consumePurchaseWith(productId, transactionId)
      .then((success) => {
        console.log(success);
      })
      .catch((error) => {
        console.error(error);
      });

Get Points

Host app can send any generic Point related information using this interface

getPoints()

API: MiniAppFeatures.getPoints

MiniApp need to call getPoints interface to retrieve Points

import MiniApp from 'js-miniapp-sdk';

MiniApp.user
    .getPoints()
    .then((points) => {
      console.log(points);
    })
    .catch((error) => {
      console.error(error);
    });

Check Android/iOS device

API: Platform.getPlatform

You can detect whether your mini app is running on an Android/iOS by using

import MiniApp from 'js-miniapp-sdk';

const platform = MiniApp.getPlatform();
//platform value here can be `Android`, `iOS` or `Unknown`.

When it is not running by Android/iOS, the return value is Unknown.

Get Host application info

API: MiniAppFeatures.getHostEnvironmentInfo

Native host application can share the information such as Locale, Host app version, Host app Build type, SDK version, device token and push token using this interface. Miniapp can fetch these information using the following interface which will get HostEnvironmentInfo as a promise.

import MiniApp from 'js-miniapp-sdk';

MiniApp
    .getHostEnvironmentInfo()
    .then((info) => {
      console.log(info);
    })
    .catch((error) => {
      console.error(error);
    });

Download File

API: MiniAppFeatures.downloadFile

Request to download a file and save to the user's device, by providing a valid fileName, URL and headers (if required).

import MiniApp from 'js-miniapp-sdk';

  MiniApp
    .downloadFile(fileName, url, { token: 'test' })
    .then((response) => {
      console.log(response);
    })
    .catch((error) => {
      console.log('FileDownload Error:', error);
    });

Secure Storage

API: SecureStorageProvider

  1. onReady

    Register/Subscribe to onReady event. Host app will send the event to Miniapp when the storage is ready

    import MiniApp from 'js-miniapp-sdk';
    
    MiniApp.secureStorageService.onReady(() => {
      // Event triggered when the storage is ready
    });
  2. onLoadError

    Register/Subscribe to onLoadError event. Host app will send the event to Miniapp when the storage is not loaded

    import MiniApp from 'js-miniapp-sdk';
    
    MiniApp.secureStorageService.onLoadError((error) => {
      console.log(error)
      // Event triggered when the storage is not loaded
    });
  3. size

    Miniapp can retrieve the storage size i.e max size and used size for a Miniapp using the below interface. It returns MiniAppSecureStorageSize as a promise.

    import MiniApp from 'js-miniapp-sdk';
    
    MiniApp.secureStorageService
      .size()
      .then((storageSize) => {
        console.log(storageSize);
      })
      .catch((error) => {
        console.log(error);
      });
  4. setItems

    If a Miniapp has available free space, you can store the values using the folowing interface. Please note the items which is set should of MiniAppSecureStorageKeyValues type

    import MiniApp from 'js-miniapp-sdk';
    
    MiniApp.secureStorageService
      .setItems(items)
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error);
      });
  5. getItem

    You can retrieve a value for a key using the below interface. As of now we are not supporting buld retrieval.

    import MiniApp from 'js-miniapp-sdk';
    
    MiniApp.secureStorageService
      .getItem(key)
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error);
      });
  6. removeItems

    List of keys that you want be removed from the storage

    import MiniApp from 'js-miniapp-sdk';
    
    MiniApp.secureStorageService
      .removeItems(keys)
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error);
      });
  7. clear

    The following interface will help you to clear all the data that is stored using the above interfaces.

    import MiniApp from 'js-miniapp-sdk';
    
    MiniApp.secureStorageService
      .clear()
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error);
      });

Host app Theme colors Available from v1.18.0

API: MiniApp.miniappUtils.getHostAppThemeColors

Host app uses different themes and if the Miniapp would like to have a similar theme as Host app, it can use the following interface to get the primary and secondary colors

Promise returns a HostThemeColor.

import MiniApp from 'js-miniapp-sdk';

    MiniApp.miniappUtils
      .getHostAppThemeColors()
      .then((info) => {
        console.log(info);
      })
      .catch((error) => {
        console.error(error);
      });

Dark Mode Available from v1.18.0

API: Platform.isDarkMode

Using the following interface the Host app can let the Miniapp know if it is Dark mode or not.

import MiniApp from 'js-miniapp-sdk';

MiniApp
  .isDarkMode()
  .then((boolean) => {
    console.log(boolean);
  })
  .catch((error) => {
    console.error(error);
  });

Send Analytics to Host app Available from v1.18.0

You can use the following interface to send analytics to Host app. Host app can use this data to record them to any server.

import MiniApp from 'js-miniapp-sdk';

  const analyticsInfo: MAAnalyticsInfo = {
    eventType: MAAnalyticsEventType.appear,
    actionType: MAAnalyticsActionType.open,
    pageName: "Home",
    componentName: "Page",
    elementType: "Tab",
    data: "AnyData",
  };
  
  MiniApp.miniappUtils.sendAnalytics(analyticsInfo);

MiniApp Finished Loading Available from v1.20.0

API: Platform.miniAppFinishedLoading

Using the following interface the Miniapp can notify the host app that it has finished loading.

import MiniApp from 'js-miniapp-sdk';

MiniApp.miniappUtils
  .miniAppFinishedLoading()
  .then((response) => {
    console.log(response);
  })
  .catch((miniAppError) => {
    console.log('miniAppFinishedLoading - Error: ', miniAppError);
  });

Get Cookies from host application Available from v1.19.0

You can use the following interface to get all Cookies from Host app using the following interface

import MiniApp from 'js-miniapp-sdk';
  
  MiniApp.cookieManager
    .getAllCookies()
    .then((response) => {
      // Response will be [CookieInfo]
      console.log(response);
    })
    .catch((error) => {
      console.log(error);
    });

You can also request the host app to provide specific cookies by sharing the list of keys as string[]

import MiniApp from 'js-miniapp-sdk';
  
  MiniApp.cookieManager
    .getCookies(['user-token', `user-last-session`])
    .then((response) => {
      // Response will be [CookieInfo]
      console.log(response);
    })
    .catch((error) => {
      console.log(error);
    });

MiniApp storage using Key/Value Available from v1.20.0

We already have a Secure storage that uses database for storing any data from MiniApp. It is recommended for MiniApps that wants to store huge data.

If MiniApp wants to use any storage that is lightweight, then they can use the following interfaces. Android uses Shared Preferences and iOS uses UserDefaults for the interfaces below,

API: MiniappPreferenceProvider

  1. set
import MiniApp from 'js-miniapp-sdk';
  
MiniApp.preferences
  .set(key, value)
  .then((response) => {
    // String response sent from Host app when the value set is successfull
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });
  1. get
import MiniApp from 'js-miniapp-sdk';
  
MiniApp.preferences
  .get(key)
  .then((response) => {
    // Value that is stored for a given key
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });
  1. remove
import MiniApp from 'js-miniapp-sdk';
  
MiniApp.preferences
  .remove(key)
  .then((response) => {
    // String response sent from Host app when the remove is successfull
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });
  1. clearMiniAppPreferences
import MiniApp from 'js-miniapp-sdk';
  
MiniApp.preferences
  .clearMiniAppPreferences(key)
  .then((response) => {
    // String response sent from Host app when the clearing preferences is successfull
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

Get feature list Available from v1.20.0

This interface will help the MiniApps to get the list of features that is supported by the MiniApp native SDK also with the list of other features that is supported by the Host app

import MiniApp from 'js-miniapp-sdk';
  
MiniApp.miniappUtils
  .getFeatureList()
  .then((response) => {
    // Array of strings/features that is supported
    // For eg., ["GET_USERNAME", "IS_DARK_MODE", "GET_ALL_COOKIES"]
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

Can open App Deeplink Available from v1.20.3

This interface will help the MiniApps to check if the URL scheme that they want to open is available in the device

import MiniApp from 'js-miniapp-sdk';
  
MiniApp.miniappUtils
  .canOpenAppDeeplink(url)
  .then((response) => {
    // True if the device contains/supports the scheme
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

App supports deeplink Available from v1.20.3

This interface will help the MiniApps to check if the application allows/whitelisted the URL that MiniApp wants to launch

import MiniApp from 'js-miniapp-sdk';
  
MiniApp.miniappUtils
  .isAppDeeplinkSupported(url)
  .then((response) => {
    // True if the application allows to launch the deeplink
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

Advanced Usage

Errors management

Access Token error

When an access token is requested, different Error subtypes can be thrown to the MiniApp:

Here is a complete example of you can manage Access Token errors:

MiniApp.user.getAccessToken("TOKEN_AUDIENCE", ["TOKEN_SCOPE1","TOKEN_SCOPE2"])
  .then(data => {
      ...
  })
  .catch(error => {                            //Example of values :
      console.error(error.name);              // AudienceNotSupportedError
      console.error(error.message);          //  The value passed for 'audience' is not supported.

      if (error instanceof AuthorizationFailureError) {
          // handle error
      } else if (error instanceof AudienceNotSupportedError) {
          // handle error
      } else if (error instanceof ScopesNotSupportedError) {
          // handle error
      } else if (error instanceof MiniAppError) {
          // handle error
      } else {
          // unexepected error caused by SDK
      }
  })

Usage when testing in the browser

Currently, the SDK does not support testing in the browser. You must test using the Android Mini App Demo App or iOS Mini App Demo App on an actual Android or iOS device.

If you wish to be able to test in a browser, you can return a mock value instead of calling the SDK method.

import MiniApp from 'js-miniapp-sdk';

const platform = MiniApp.getPlatform();

function getId() {
  if (platform != 'Unknown') {
    return MiniApp
      .getUniqueId()
      .then(id => {
        console.log(id);
      })
      .catch(error => {
        console.error(error);
      });
  } else {
    return Promise.resolve('mock_unique_id_value');
  }
}

Troubleshooting & FAQs

This is an error that you could see on Android devices when using any of the SDK functions.

Please ensure that you have defined a <title> tag within your HTML document's <head> before the Mini App SDK <script> tag. For example:

<head>
  <title>My Mini App title</title>
  <script src="miniapp.bundle.js"></script>
  <head></head>
</head>

In the Android SDK, we will inject some necessary JavaScript from the native side, and we do this after receiving a callback that the mini app's <title> has been set. So if you do not set a <title>, then the JavaScript will be injected at an unpredictable time and you could see errors when trying to use SDK functions.

Changelog

See the full CHANGELOG.