Joke: About the wechat custom sharing before and after turning over the document two or three times, feel that the big guys write documents are so cool? Hiding in the corner of my shiver for two days…..

Let’s look (in anger) at the wechat documentation for development: portal

1. Configure according to the document (public number security domain name, introducing official wechat JS)

2. Configure permissions according to the wechat documentation: All pages that need to use JS-SDK must be injected with configuration information first

wx.config({
    debug: true// If debug mode is enabled, the return value of all API calls will be displayed in the client side alert. To view the passed parameters, you can open it in the PC side and the parameter information will pass throughlogPrint, print only on PC. appId:' 'Timestamp:, // Mandatory, generated signature's timestamp nonceStr:' ', // mandatory, generate a random string signature:' ',// Required, signed jsApiList: [] // Required, list of JS interfaces to use}); ----->>>>> Obtain the preceding information (* mandatory) by invoking the background interface and initialize the configuration in MountedCopy the code

3. Verify the success of the ready interface processing (directly in the ready method to share friends and friends)

wx.ready(functionWx. onMenuShareTimeline ({title: 'title', desc: 'desc', // Share description link: 'their shared routing address', share link, the link domain name or path must be consistent with the current page corresponding public number JS security domain nameCopy the code
ImgUrl: 'Customize icon', // Share icon success:function () {
    },
    cancel: function() {}}); Wx. onMenuShareAppMessage({title: 'title', desc: 'desc', link: ImgUrl: 'Custom icon', // Share iconCopy the code
    success: function () {
    },
    cancel: function() {}}); wx.error(function(){
    salert('Verification failed');
  });
});Copy the code

Through the above three steps, wechat to share friends and circle of friends function is completed, very happy to open the local wechat developer tool debugging >>> successfully !!!!

Tell PR that the feature is ready and live with pride.

Two days later PR came to me and said that there was something wrong with wechat sharing, WTF?? One day it was fine, but then it went wrong. Here’s a screenshot shared online:



Then I started to troubleshoot the problem one by one. First I checked the wechat whitelist, wx.config configuration items, background data, and asynchronous initialization. Then I went to the developer tools and found no problems. So I pushed it up again and found that I still could not share it. I went to wechat to look at the document and found that there was no illegal font and any content violating wechat document. Repeatedly share and discover a pattern.

Here we go!!

Only in the first share title and lost connection, refresh the current page and then share successfully, so Google search, found that wechat is not so friendly to SPA single page sharing (suddenly reminds me of IE before…). The first link you share under ios is always the first URL you visit. See below:



It takes a refresh on ios to share correctly and save the current URL

Solutions:

Create a new share.js file under SRC /assets/js, register globally in main.js, identify ios terminal through beforeRouteEnter hook at the same time each component is called, and then load a new document using assign(). This wechat custom sharing ended……….. , take a look at the results of successful customization sharing:



BeforeRouteEnter implementation method:

beforeRouteEnter (to, from, next) { var u = navigator.userAgent; var IOS = !! u.match(/\(i[^;] +; ( U;) ? CPU.+Mac OS X/); //ios terminal // Fix ios version wechat HTML5 History compatibility issueif(IOS && to.path ! Location. replace location.assign(to.fullpath)} == location. pathName) {// Cannot use location.replace location.assign(to.fullpath)}else {
    next()
  }
}Copy the code

Share.js is the implementation method:

// Ajax to request wexinfunction getWxChat() {
     return new Promise((resolve, reject) => {
       $.ajax({
         url: 'https://res.wx.qq.com/open/js/jweixin-1.0.0.js',
         dataType: "script",
         cache: true,
      })
      .done(function () {
       resolve(window.wx)
      })
      .fail(function(error) { reject(error); }); })} // Background request signature algorithmfunction backAround() {
    returnNew Promise((resolve, reject) => {$. Ajax ({url: 'XXX.com',//'POST',
        data: {
          url: window.location.href.split(The '#')[0],
        },
        type : 'json'
      }).done(function(ret) {
        resolve(ret)
      }).fail(function(ret) { reject( ret ); })})}export function wechatShare(shareDate) {
  return new Promise(async function(resolve, reject) {
    try{
      let isWechat=navigator.userAgent.indexOf('MicroMessenger')> 1 // It is a wechat browserif(! isWechat){return resolve('not weichat')}if(! window.wx){ await getWxChat(); } var defaultData = {title: 'share title', content: 'content', link: '${window.location.href}', logo: ', // Success of shared image:function (res) {
        },
      }

      letdata = { ... defaultData, ... shareDate }let ret = JSON.parse(await backAround())

      wx.config({
        debug: false// Enable debug mode, appId:'XXXXX'Timestamp: ret.timestamp, // Required, generated signature timestamp nonceStr: ret.nonce_str, // Required, generated signature random string signature: Ret.signature,// Required, signature, see Appendix 1'onMenuShareAppMessage'.'onMenuShareTimeline']
      })

      wx.ready(function () {

        wx.onMenuShareTimeline({
          title: data.title,
          desc: data.content,
          link: data.link,
          imgUrl: data.logo,
          dataUrl: ' ',
          success: data.success,
          cancel: function () {}
        })

        wx.onMenuShareAppMessage({
          title: data.title,
          desc: data.content,
          link: data.link,
          imgUrl: data.logo,
          dataUrl: ' ',
          success: data.success,
          cancel: function() {} }) }) }catch(error){ reject( error ); }})}Copy the code

Finally, I would like to say that I am actually recording my own history of blood and tears when WRITING the content, and I would also like to share with you the problems of wechat custom sharing. Sometimes the wechat documents make people doubt life and Codeing. If you have a better solution, please share with us.