Skip to content

Open Ability Components

Open ability components provide access to platform-specific features and capabilities, such as user authorization, sharing, payment, and other system-level functionalities.

web-view

The web-view component is a container that can host web pages and automatically fills the entire page.

Properties

PropertyTypeDefaultDescription
srcStringURL of the web page
allowStringSpecifies the capabilities that web-view can use
sandboxStringSecurity restrictions for the web-view component
webview-stylesObjectStyles for the webview
progressBooleantrueWhether to show progress bar

Events

EventDescriptionReturn Value
@messageTriggered when web page posts message to appevent.detail =
@onPostMessageReal-time message from web page

Example

vue
<template>
  <view>
    <web-view :src="url" @message="handleMessage"></web-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      url: 'https://uniapp.dcloud.io/'
    }
  },
  methods: {
    handleMessage(event) {
      console.log('Message from web page:', event.detail.data);
      uni.showModal({
        content: 'Received message: ' + JSON.stringify(event.detail.data)
      });
    }
  }
}
</script>

The ad component is provided by mini-program platforms for displaying advertisements.

Properties

PropertyTypeDefaultDescription
unit-idStringAd unit ID, can be obtained from platform ad console
ad-intervalsNumberAuto-refresh interval in seconds, minimum 30
ad-typeStringfeedAd type: banner, video, feed, interstitial
ad-themeStringwhiteAd theme: white, black

Events

EventDescriptionReturn Value
@loadAd loaded successfullyevent
@errorAd loading failedevent.detail =
@closeAd closedevent

Example

vue
<template>
  <view class="content">
    <view class="ad-container">
      <ad 
        :unit-id="adUnitId"
        ad-type="feed"
        ad-theme="white"
        @load="adLoad"
        @error="adError"
        @close="adClose"
      ></ad>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      adUnitId: 'your-ad-unit-id' // Replace with your ad unit ID
    }
  },
  methods: {
    adLoad(e) {
      console.log('Ad loaded successfully');
    },
    adError(e) {
      console.error('Ad loading failed:', e.detail);
    },
    adClose(e) {
      console.log('Ad closed');
    }
  }
}
</script>

<style>
.content {
  padding: 15px;
}
.ad-container {
  margin-top: 20px;
}
</style>

official-account

The official-account component is provided by WeChat Mini Program for displaying official account follow component.

Properties

This component has no properties.

Events

EventDescriptionReturn Value
@loadComponent loaded successfullyevent
@errorComponent loading failedevent.detail =

Example

vue
<template>
  <view class="content">
    <official-account @load="accountLoad" @error="accountError"></official-account>
  </view>
</template>

<script>
export default {
  methods: {
    accountLoad(e) {
      console.log('Official account component loaded successfully');
    },
    accountError(e) {
      console.error('Official account component loading failed:', e.detail);
    }
  }
}
</script>

open-data

The open-data component is used to display platform open data.

Properties

PropertyTypeDefaultDescription
typeStringOpen data type
langStringenLanguage: en, zh_CN, zh_TW
default-textStringDefault text when data is empty
default-avatarStringDefault avatar when user avatar is empty

type Values

ValueDescriptionPlatform Support
userNickNameUser nicknameWeChat, QQ, Baidu, Alipay Mini Programs
userAvatarUrlUser avatarWeChat, QQ, Baidu Mini Programs
userGenderUser genderWeChat, QQ, Baidu Mini Programs
userCityUser cityWeChat, QQ, Baidu Mini Programs
userProvinceUser provinceWeChat, QQ, Baidu Mini Programs
userCountryUser countryWeChat, QQ, Baidu Mini Programs
userLanguageUser languageWeChat, QQ, Baidu Mini Programs

Example

vue
<template>
  <view class="content">
    <view class="user-info">
      <view class="avatar">
        <open-data type="userAvatarUrl"></open-data>
      </view>
      <view class="info">
        <view class="nickname">
          <text>Nickname: </text>
          <open-data type="userNickName" default-text="Not logged in"></open-data>
        </view>
        <view class="gender">
          <text>Gender: </text>
          <open-data type="userGender" lang="en"></open-data>
        </view>
        <view class="location">
          <text>Location: </text>
          <open-data type="userCountry" lang="en"></open-data>
          <open-data type="userProvince" lang="en"></open-data>
          <open-data type="userCity" lang="en"></open-data>
        </view>
      </view>
    </view>
  </view>
</template>

<style>
.content {
  padding: 15px;
}
.user-info {
  display: flex;
  align-items: center;
}
.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20px;
}
.info {
  flex: 1;
}
.nickname, .gender, .location {
  margin-bottom: 10px;
}
</style>

login-button

The login-button component is used for Alipay authorization login in Alipay Mini Program.

Properties

PropertyTypeDefaultDescription
imageStringButton image URL
sizeStringnormalButton size: normal, mini
typeStringprimaryButton type: primary, default
disabledBooleanfalseWhether disabled
loadingBooleanfalseWhether showing loading state

Events

EventDescriptionReturn Value
@getAuthorizeTriggered when user clicks authorize buttonevent.detail =
@errorTriggered when authorization failsevent.detail =

Example

vue
<template>
  <view class="content">
    <login-button
      type="primary"
      @getAuthorize="onGetAuthorize"
      @error="onAuthError"
    >Alipay Authorization Login</login-button>
  </view>
</template>

<script>
export default {
  methods: {
    onGetAuthorize(e) {
      console.log('Authorization code:', e.detail.authCode);
      // Send auth code to server to exchange for user info
      uni.showLoading({ title: 'Logging in...' });
      // Simulate server request
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({ title: 'Login successful' });
      }, 2000);
    },
    onAuthError(e) {
      console.error('Authorization failed:', e.detail.error);
      uni.showToast({
        title: 'Authorization failed',
        icon: 'none'
      });
    }
  }
}
</script>

<style>
.content {
  padding: 15px;
  display: flex;
  justify-content: center;
  margin-top: 50px;
}
</style>

subscribe

The subscribe component is used for subscription messages, only supported in WeChat Mini Program.

Properties

PropertyTypeDefaultDescription
template-idStringTemplate ID
subscribe-idStringSubscription message ID

Events

EventDescriptionReturn Value
@successSubscription successful callbackevent
@errorSubscription failed callbackevent

Example

vue
<template>
  <view class="content">
    <button @click="showSubscribe">Subscribe Message</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      templateId: 'your-template-id' // Replace with your template ID
    }
  },
  methods: {
    showSubscribe() {
      // Call WeChat Mini Program subscription message API
      uni.requestSubscribeMessage({
        tmplIds: [this.templateId],
        success: (res) => {
          console.log('Subscription result:', res);
          if (res[this.templateId] === 'accept') {
            uni.showToast({
              title: 'Subscription successful',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: 'Subscription failed',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('Subscription failed:', err);
          uni.showToast({
            title: 'Subscription failed',
            icon: 'none'
          });
        }
      });
    }
  }
}
</script>

<style>
.content {
  padding: 15px;
  display: flex;
  justify-content: center;
  margin-top: 50px;
}
</style>

button (Open Ability)

The button component with open-type attribute provides access to various platform capabilities.

Basic Usage

vue
<template>
  <view class="container">
    <!-- Get user info -->
    <button open-type="getUserInfo" @getuserinfo="onGetUserInfo">
      Get User Info
    </button>
    
    <!-- Get phone number -->
    <button open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
      Get Phone Number
    </button>
    
    <!-- Share -->
    <button open-type="share" @click="onShare">
      Share
    </button>
    
    <!-- Contact customer service -->
    <button open-type="contact" session-from="custom-session">
      Contact Service
    </button>
    
    <!-- Open settings -->
    <button open-type="openSetting" @opensetting="onOpenSetting">
      Open Settings
    </button>
  </view>
</template>

<script>
export default {
  methods: {
    onGetUserInfo(e) {
      console.log('User info:', e.detail);
      if (e.detail.userInfo) {
        // User authorized
        this.userInfo = e.detail.userInfo;
      } else {
        // User denied authorization
        uni.showToast({
          title: 'Authorization denied',
          icon: 'none'
        });
      }
    },
    
    onGetPhoneNumber(e) {
      console.log('Phone number:', e.detail);
      if (e.detail.encryptedData) {
        // Send encrypted data to server for decryption
        this.decryptPhoneNumber(e.detail);
      }
    },
    
    onShare() {
      // Share logic will be handled by the platform
      console.log('Share button clicked');
    },
    
    onOpenSetting(e) {
      console.log('Settings result:', e.detail);
      // Check authorization status
      if (e.detail.authSetting['scope.userInfo']) {
        console.log('User info authorization granted');
      }
    },
    
    decryptPhoneNumber(detail) {
      // Send to server for decryption
      uni.request({
        url: 'https://api.example.com/decrypt-phone',
        method: 'POST',
        data: {
          encryptedData: detail.encryptedData,
          iv: detail.iv,
          sessionKey: this.sessionKey // Get from login
        },
        success: (res) => {
          console.log('Decrypted phone:', res.data.phoneNumber);
        }
      });
    }
  }
}
</script>

open-type Values

ValueDescriptionPlatform SupportEvent
getUserInfoGet user infoMini-program@getuserinfo
getPhoneNumberGet phone numberMini-program@getphonenumber
getUserProfileGet user profileWeChat Mini-program@getuserprofile
shareShareMini-program-
contactContact customer serviceWeChat Mini-program@contact
openSettingOpen authorization settingsMini-program@opensetting
launchAppLaunch AppWeChat Mini-program@launcherror
feedbackFeedbackWeChat Mini-program-
chooseAvatarChoose avatarWeChat Mini-program@chooseavatar
agreePrivacyAuthorizationAgree privacy authorizationWeChat Mini-program@agreeprivacyauthorization

Platform Differences

Different open ability components have varying support across platforms:

  1. web-view component is supported on most mainstream platforms, but may have domain whitelist restrictions in mini-programs.

  2. ad component is mainly supported on mini-program platforms, with different ad types and configurations across platforms.

  3. official-account component is only supported on WeChat Mini Program platform.

  4. open-data component is mainly supported on mini-program platforms, with different supported data types across platforms.

  5. login-button component is only supported on Alipay Mini Program platform.

  6. subscribe component is only supported on WeChat Mini Program platform.

When using these components, please refer to the latest documentation of each platform to ensure correct usage.

Important Notes

  1. When using open ability components, pay attention to platform-specific permission and configuration requirements, such as domain whitelists, ad unit IDs, etc.

  2. Some open abilities may require specific mini-program categories or certification requirements. Please confirm that your application meets the conditions before use.

  3. When using the web-view component, pay attention to communication methods and security restrictions between web pages and mini-programs.

  4. The display effect and revenue of ad components are related to various factors such as traffic quality, ad placement, user demographics, etc. It is recommended to conduct reasonable testing and optimization.

  5. When using open data, ensure that users have authorized access to relevant information, otherwise it may not display properly.

  6. Subscription message functionality has usage frequency and count limitations. Please design the subscription process reasonably and avoid frequent subscription requests from users.

Best Practices

  1. Handle Authorization Gracefully: Always provide fallback options when users deny authorization.

  2. Respect User Privacy: Only request necessary permissions and clearly explain why they are needed.

  3. Test Across Platforms: Different platforms may have different behaviors for the same component.

  4. Error Handling: Implement proper error handling for all open ability components.

  5. User Experience: Provide clear feedback to users about what will happen when they interact with open ability components.

For more information about open ability components, refer to the uni-app official documentation.

一次开发,多端部署 - 让跨平台开发更简单