WeChat Mini Program Share Configuration
When developing WeChat mini programs, you need to configure the sharing functionality. Here I'll document the issues I encountered when configuring sharing.
Share configuration can be done globally or locally.
In WeChat's official documentation, there doesn't seem to be explicit global share configuration. You can only configure sharing information in each page. But we can use some tricks to implement global share configuration.
So, the official documentation doesn't explicitly state the priority between global and local configuration. In my opinion, local configuration should have higher priority, because local configuration is done in the page and can better combine with business attributes; while global configuration is done when the mini program starts.
Global Configuration
For global sharing, you need to configure sharing information in the mini program's app.js, so all pages can have the same default sharing information. After all, you can choose to configure sharing information separately in individual pages, while other pages use the default sharing information.
We need to inject a self-executing function in it, which will execute when the mini program starts, so we can configure sharing information globally in it.
If it's a Taro mini program, this app.js file is in src/app.js.
/**
* @description Share mini program - Global unified default configuration
*/
;(() => {
let PageTmp = Page
Page = function(pageConfig) {
// Set global default sharing
pageConfig = Object.assign(
{
onShareAppMessage: function() {
return {
title: 'Default Share Title',
path: '/pages/index/index',
}
},
},
pageConfig
)
PageTmp(pageConfig)
}
})()From the code, we can see that we modified pageConfig in the Page function, adding an onShareAppMessage method. This method returns an object to implement the mini program's share configuration. This implements global share configuration. Or it might be more accurate to call it default share configuration. It corresponds to the onShareAppMessage lifecycle method in @tarojs/taro.
Using Object.assign here, the important thing is to understand that it's used to merge the default share configuration with the local page's pageConfig. In this merge, we need to give the local page's configuration higher priority, meaning if there are values with the same key, the local configuration will override the global configuration. Therefore, when setting sharing information in a specific page, that information will override the default settings. If a page doesn't set sharing information, the default settings will be used. If the merge order is reversed, the global configuration will always be used.
Local Configuration in Global Configuration
In global configuration, we can use some tricks to implement local configuration. This way, we can configure some default sharing information in global configuration, but in certain pages, we can override these default sharing information.