Small program development process encountered problems and solutions

1. How to keep the login status in the small program

Problem: Cookies are commonly used to maintain login status on web pages, but there is no such thing as cookies in applets

Solution: The login status can be saved in storage, which is equivalent to localStorage in the web page. Each time the small program is initialized, the login token in the storage is taken out and submitted in the header of the request. The backend needs to retrieve the token from the header for authentication

2. How to synchronize and maintain login status in the web-view of the applet

Problem: Since the applet and the web page are two separate systems, each maintains its login status independently, the login status needs to be passed in when opening the web page in the applet, and must be maintained in subsequent pages

Solution:

  1. When opening a web page, concatenate the login token in the parameters of the WEB page URL. The web page needs to extract the login token from the URL and save it in localStorage for use in subsequent pages.
  2. To be compatible with the cookie mode of the web page and the URL parameter mode of the mini program, a unified method to obtain the login status should be added to the web page: Check whether the URL has a token -> Check whether the localStorage has a token -> Use the cookie.

3. The small program uses canvas to process pictures, but does not display canvas elements

Problem: In the small program, canvas is used for image stitching. Sometimes we do not need to display the canvas, but only need to use the image processed by the canvas.

Solution (choose one of the two) :

  1. Components that use the cover-class are overlaid on the canvas, such as the cover-View
  2. Position the Canvas element in absolute position outside the top of the page

4. Open a web page in a small program

Problem: In applets, we may open various Web pages, and creating one page for each page is definitely the worst way, so we need to use one page for each Web page.

Solution: Encapsulate the unified method of opening the page, deal with the concatenation of parameters, deal with the domain name in different environments:

/** * Use webView to open url *@param {string} url url
     * @param {object} Query Query parameter */
    openWebPage(url, query) {
      let oepnUrl = url;

      / / parse the hash
      const hasHash = url.includes("# /");
      consthash = !! hasHash ?"# /" + oepnUrl.split("# /") [1] : "";

      // Parse the parameters
      let queryUrl = oepnUrl.split("# /") [0];
      const hasSearch = queryUrl.includes("?");
      letsearch = !! hasSearch ?`?${queryUrl.split("?") [1]}` : "";
      let newQuery = {};
      if (search) {
        newQuery = util.parseQueryString(search);
      }

      // Check whether the token is included in the whitelist. The whitelist needs to be configured by the developer
      for (let i = 0; i < config.host_white_list.length; i++) {
        if (oepnUrl.includes(config.host_white_list[i])) {
          newQuery["miniprogram_t"] = wx.getStorageSync(config.LoginTokenKey); }}// Add a custom parameter
      if(query) { newQuery = { ... newQuery, ... query }; }// Synthesize string arguments
      const queryString = util.joinQueryString(newQuery);

      / / stitching url
      const finalUrl = queryUrl.split("?") [0] + queryString + hash;

      / / jump webView
      wx.navigateTo({
        url: `/pages/webpage/webpage? url=The ${encodeURIComponent(finalUrl)}`})},Copy the code

5. Set the sharing content of the applet on the web-view page

Problem: Because the web page needs to be compatible with wechat web page sharing and small program sharing, the communication between web pages and small program is involved, and different processing needs to be done according to the environment.

Solution:

  1. To determine the environment
util.checkWechatEnv = function(callback) {
  var ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) = ="micromessenger") {
    // Check whether it is wechat environment
    // wechat environment
    wx.miniProgram.getEnv(function(res) {
      if (res.miniprogram) {
        // In a small program environment
        callback("miniprogram");
      } else {
        // Non-applets environment
        callback("wechat"); }}); }else {
    // Non-wechat environment
    callback("outOfWechat"); }};Copy the code
  1. Set the share
/ / environment
let env = "";
// Whether sharing is initialized
let hasInitShare = false;
Copy the code
// Set wechat sharing
const wxShare = (shareData = {}) = > {
  // Merge to share information
  const sData = Object.assign(config.wechat.shareData, shareData);

  const creatShare = function(data) {
    if (env == "miniprogram") {
      / / in a small program, the use of wx. MiniProgram. PostMessage and communication program
      wx.miniProgram.postMessage({ data: { shareData: data } });
    }

    // Non-applets in wechat
    if (env == "wechat") {
      / / set
      const set = function(data) {
        wx.ready(() = > {
          wx.onMenuShareAppMessage(data); // Share with friends
          wx.onMenuShareTimeline(data); // Share it on moments
          wx.onMenuShareQQ(data); // Share to QQ
          wx.onMenuShareWeibo(data); // Share to weibo
          wx.onMenuShareQZone(data); // Share to QZone
        });
      };

      if(! hasInitShare) {// Initialize wechat sharing
        share({
          appId: config.wechat.appId,
          shareUrl: location.href
        }).then(res= > {
          // Set the initialization information
          wxConfigData.timestamp = res.data.timestamp;
          wxConfigData.nonceStr = res.data.nonce;
          wxConfigData.signature = res.data.signature;

          if (typeofwx ! = ="undefined") {
            hasInitShare = true; // Change the initialization state
            wx.config(wxConfigData); // Initialize the configuration
            set(data); // Set the content to share}}); }else {
        if (typeofwx ! = ="undefined") {
          set(data); // Set the content to share}}}};// If the environment is known, set sharing. If the environment is unknown, check the environment first and then set sharing
  if(!!!!! env) { creatShare(sData); }else {
    util.checkWechatEnv(res= >{ env = res; creatShare(sData); }); }};Copy the code
  1. Small program to get shared data
// wxml
<web-view src="{{url}}" wx:if="{{!!!!! url}}" bindmessage="postmessage"></web-view>
Copy the code
// js
postmessage(e) {
    const detail = e.detail;
    this.shareData = detail.data[0].shareData;
}
Copy the code

Ps: a small program in wx. MiniProgram. PostMessage trigger

6. Small program upload pictures

Problem: Usually our images are submitted to the back end as BLOb or Base64. However, there are two ways to get image files in applets: Wx.chooseimage and wx.canvastotempFilepath both get temporary paths to image files and cannot be directly converted to BLOb or Base64.

Solution: The applet provides the wx.uploadFile method to convert a file from a temporary path into a BLOB and submit it to the specified back-end interface.

wx.uploadFile({
  url: url, // Address of the back-end interface
  filePath: tempFilePath, // Temporary path in applet
  name: "file".success(res) {
    resolve(JSON.parse(res.data));
  },
  fail(res){ reject(res); }});Copy the code

7. Small program swiper specifies the display-multiple-items bug

Problem: When the number of display-multiple-items is specified, if the actual number of swiper-items is smaller than the specified value, nothing will be displayed

Solution: Get the actual number of elements, fill the empty element with the value specified by display-multiple-items

8. H5 embedded in the small program to deal with the problem of not logging in or login status expired

Problem: When the applet opens the H5 page, a token is passed in to pass the login status, but the token may expire and the login process needs to be completed again

Solution:

  1. In H5, you need to wrap the request function for unlogged processing
  2. When the interface returns to the unlogged state, check the web page environment. If it is in the applet environment, go to the applet login page
  3. The web-view component of the applet provides an open interface that gives Web pages the ability to jump to the applet pages
<script
  type="text/javascript"
  src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"
></script>
Copy the code
wx.miniProgram.navigateTo({ url: "/path/login/login? from=web" });
Copy the code
  1. The parameter “from=web'” is added to the preceding jump address to refresh the web page login status in the logic of the applet. When the applet login page receives “from=web'”, it can store the mark in the cache of the applet
  2. After login, return to the Web page, and the applet searches for the token in the cache. If the token exists, the applet obtains the new token from the cache and modifies the link parameters in the Web page to update the login status

9. Processing of rich text data in small programs

Q: Sometimes, our data is edited in the background as rich text, that is, HTML strings, such as articles, item details. How do we deal with rich text and images in rich text

Solution:

  1. The applet provides a rich-text component to display rich text strings, as shown below
<rich-text nodes="{{htmlText}}"></rich-text>
Copy the code
  1. However, in the background editing content, the size of the image is not certain, which may be very large, and it cannot be looked at directly in the small program. Therefore, the style of the IMG tag needs to be modified, and the image width can be uniformly processed to 100% width. The code is as follows:
let newHtmlText = oldHtmlText.replace(
  /\<img/g.'
);
this.setData({
  htmlText: newHtmlText
});
Copy the code
  1. More rich text usage instructions rich-text