scenario

  • Due to some special requirements, the project is separated. The current project is in the official account of wechat, and part of the requirements require the use of mini program. However, there is a correlation between the two, so it is necessary to use the official account to jump to the mini program.

Technical solution

  • Use JSSDK of wechat webpage

Apply to the environment

  • Wechat version requirements:7.0.12And above
  • The system version must be:IOS 10.3And above,The Android 5.0And above

Specific steps

  • This part is in the official document, I am moved to facilitate you to see, you can also go to the official document to see.The official documentation
  1. Binding domain

    • First, log in the wechat public platform, enter the “function Setting” of “public Account Setting”, and fill in the “JS interface security domain name”.
  2. Importing JS files

    • When you need to callJSThe interface page is introduced as followsJSFiles, (supporthttps) :http://res.wx.qq.com/open/js/jweixin-1.6.0.js
    • To further improve service stability, you can access the following resources if they are unavailable:http://res2.wx.qq.com/open/js/jweixin-1.6.0.js(supporthttps).
    • Note: SupportedAMD/CMDStandard module loading method loading
  3. Verify the configuration through the config interface injection permission

    • All requiredJS-SDKThe page must first inject configuration information, or it will not be calledurlIt only needs to be called once, for changesurlSPAweb appIn every timeurlChange when called at presentAndroidWechat client is not supportedpushStateH5New feature, so usepushStateTo implement theweb appThe page will cause the signature to failAndroid6.2Repair).
    Wx. config({debug: true, // Enable debug mode, the return value of all API calls will be alert in the client, if you want to view the passed parameters, you can open it in the PC, parameter information will be printed in the log, only on the PC. Timestamp:, // Required, generate signature's timestamp nonceStr: ", // Required, generate signature's random string signature: ", // Required, signature jsApiList:" [], // Mandatory. Appentaglist: [' wX-open-launch-appellate '] // appellate: < wX-open-launch-appellate >});Copy the code
  4. Successful validation through the ready interface processing

    Wx.ready (function(){// The ready method is executed after the config information is validated. All interface calls must be made after the config interface. Config is an asynchronous operation on the client side, so if the relevant interface needs to be called when the page loads, The relevant interface must be called in the ready function to ensure correct execution. Interfaces that are invoked only when triggered by the user can be invoked directly without being placed in the ready function. });Copy the code
  5. Failed validation through the error interface

    Wx. error(function(res){// If the config information fails to be verified, the error function will be executed. For example, if the signature expires, the verification fails. You can run the debug mode of config or view the error information in the res parameter returned. You can update the signature here for SPA. });Copy the code
  6. After the initialization, add the following labels to the page

PostUrl ({url: curUrl}). Then (res => {if (res.code === 0) {wx.config({debug: postUrl({url: curUrl}). False, // If debug mode is enabled, the return value of all API calls will be alert on the client. If you want to view the passed parameter, you can open it on the PC, and the parameter information will be printed in log. AppId: res.data.appId, // Required, the unique identifier of the public number timestamp: res.data. timestamp, // Required, the timestamp of the generated signature nonceStr: Res.data. nonceStr, // Required, generates a random string of signatures signature: res.data.signature, // Required, jsApiList: ['onMenuShareAppMessage'], openTagList: [' wX-open-launch-downloadp '] // Optional, list of opentags to use, for example, [' wX-open-launch-app ']}); wx.ready(function(){}) wx.error(function(error){}) } }) // html <wx-open-launch-weapp id="launch-weapp1" username="gh_xxxxxx" path="xxxxxx" @launch="onLaunch" @error="onError" > <script type="text/wxtag-template"> <div style="font-size: 14px; margin-top: 10px; text-align: center;" "> </div> </script> </ wx-open-launch-downloadp >Copy the code

(1) username: the original id of the small program to be opened starts with gh_; HTML should be added at the end of the page, for example: ‘pages/index/index.html’, otherwise the page of the small program will not be configured when IOS jumps.

Error handling

  1. Label error

  • Solution: Inmain.jsAdd the following code to;
// main.js
Vue.config.ignoredElements = ['wx-open-launch-weapp'];
Copy the code
  1. wx-open-launch-weappIn theDomDon’t show
  • The currentwx-open-launch-weappIn the tagDomOnly under the real machine will be displayed, in the browser on the PC, wechat developer tools will not be displayed;This leads to a problemwx-open-launch-weappContent control, style debugging and so on are difficult, and rendering data is troublesome.
  1. wx-open-launch-weappIn theDomDisplay, but the real machine click no response
  • If the tag used allows slots to be provided, care needs to be taken to define the style of the template in the slot, since the style of the template in the slot is isolated from the page. Slot templates and styles are required to pass<template></template>Wrap up.forVueSuch view frames in order to avoidtemplateTag conflict issues can be used<script type="text/wxtag-template"><script>To replaceTo wrap slot templates and styles.
  1. Applets cannot be opened
  • This way can only open legal small program and small program has been officially released (experience version not).

To optimize the

  • When we need to pass a card or have a lot of dynamic data render a big oneDomWhen structuring, the style inside is very troublesome to write and the data inside is also very inconvenient to set dynamically, so our best way is not towx-open-launch-weappWrite anything in.
  • After my own try, I gave up inwx-open-launch-weappWrite style, because it is in too much trouble, a change on the need to deploy, to the real machine verification.

The solution

  • Create a wrap where you want to jump, overlay the wrap over the click area, and set the background color to transparent. And dynamically generatewx-open-launch-weapp
  1. Add a wrap
<div class=" appellate p-cover"></div> // appellate p-cover should be set dynamically based on the click region. position: absolute; bottom: 16px; right: 26px; // background-color: red; }Copy the code
  1. Dynamically set the width and height of the cladding layer
mounted() { const weappDom = this.$el.querySelector('.weapp-cover'); const menuItemDom = this.$el.querySelector('.menu-item'); // appaggregate pdom.style.width = menuitemdom. clientWidth + 'px'; weappDom.style.height = menuItemDom.clientHeight + 'px'; }Copy the code
  1. Dynamically generatedwx-open-launch-weapp
/ * * * @ description: generates wx - open - launch - weapp * @ param / / {Object} info * * * @ description: info parameter let params = {width: "", click on the area width height:" ", click on the area highly ele: "", / / element ID appid:" ", / / small program ID gh_ * * * * url: "", / / jump page path address of small programs Ex. : Pages /home/home. HTML - (the suffix must be added with the. HTML suffix otherwise, the small program page is not configured when IOS switches.) content:"" // HTML String example: "<button> appellate </button>"} */ export function wx_launch(info) {const BTN = info.el.queryselector ('.appellate '); Const script = document.createElement("script"); Type = "text/wxtag-template"; // Type script.text = info.content // User-defined HTML string content const HTML = '< wX-open-launch-downloadp style="width:${info.width}; height:${info.height}; display:block;" username="${info.appid}" path="${info.url}">${script.outerHTML}</wx-open-launch-weapp>`; btn.innerHTML = html; // HTML string assignment}Copy the code
  1. Added wechat browser judgment
/ / determine whether WeChat environment function is_weixn () {let ua. = the navigator userAgent. ToLowerCase () if (ua) match (/ MicroMessenger/I) = = 'micromessenger') { return true } else { return false }; };Copy the code
  1. Add wechat version judgment
  • During the test, it was found that the wechat of some staff always suggested that your version number was not supported. Through checking each wechat version, it was found that the wechat version strings obtained were inconsistent, with some being three or four characters.
const wxInfo = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i); WxInfo [1] = "8.0.1840" // Abnormal version wxInfo[1] = "8.0.1.1840"Copy the code
  • Wechat version requirements:7.0.12And above
  • Through the above questions, we can modifyis_versionMethod, first judge the large version number and the first greater than7Return directly whentrueWhen is equal to the7, determine whether the second is greater than0, is more than0Direct returntrueIs equal to0Is used to determine whether the third digit is greater than or equal to12. The code is as follows:
/ / determine whether the current WeChat version support function is_version () {const wxInfo. = the navigator userAgent. Match (/ MicroMessenger \ / (/ \ \ d +)/I). // wechat browser information // wechat normal version wxInfo[1] = "8.0.1840" (example) // wechat abnormal version wxInfo[1] = "8.0.1.1840" (example) // Split into arrays for judgment [' 8 ', '0', '1', '1840'] (sample) const version = wxInfo [1]. The split (". "); // console.log('version', version); If (Number(version[0]) > 7) {return true; } else if (Number(version[0]) === 7) { if (Number(version[1]) > 0) { return true; } else if (Number(version[1]) === 0) { if (Number(version[2]) >= 12) return true; } } return false; }Copy the code
  • Note: string callssplitMethod after the number in the array is a string.
  1. Modify dynamic generationwx-open-launch-weappmethods
export function wx_launch(info) { + if (! is_weixn()) { + return + } + if (is_version()) { const btn = info.ele.querySelector('.weapp-cover'); // Get the element... +} else {+ alert(" Your version is not supported ") +}Copy the code
  1. callwx_launch
mounted() { const weappDom = this.$el.querySelector('.weapp-cover'); const menuItemDom = this.$el.querySelector('.menu-item'); // appaggregate pdom.style.width = menuitemdom. clientWidth + 'px'; weappDom.style.height = menuItemDom.clientHeight + 'px'; $el + wx_launch({+ ele: this.$el, + width: menuItemdom. clientWidth + 'px', + height: menuItemDom.clientHeight + 'px', + appid: 'gh_xxxx', + url: this.miniProgramPath, + content: + `<style> + .res-cover { + width: ${menuItemDom.clientWidth}px; + height: ${menuItemDom.clientHeight}px; + } + </style> + <div class="res-cover"></div>` + }) }Copy the code

conclusion

  • After getting the requirements, the first is to go to whether there are relevant technical solutions to achieve such a function; There are technical solutions, through the analysis of the needs to see how to achieve and may encounter problems;
  • Pit you’ve encountered: error handling4I have encountered all these problems.wx-open-launch-weappIn the content display style problem and card data can not dynamically render problems, dynamic generationwx-open-launch-weappDomI can’t find it and so on.
  • After the function has been implemented, we can achieve our expectations through some strange techniques or indirect methods, do not be limited by the requirements of the thinking.

supplement

  • Follow-up questions are added here
    1. URLJump applet with parameters, applet receive incomplete, jumpURLAs follows:

    What the applet receives is"Source=public&token={"The reason is thattokenIs an object passed throughJSON.stringifyGenerated string,URLAn insert generated from a template stringtokenGenerated, causing the applet to receive the truncated quotes, so we need to use them in the generated object type stringencodeURIforURLEncoding.

    const pathStr = 'pages/detail/speakingDetail.html? Source=public'; let tokenParams = {}; const miniProgramUrl = `${pathStr}&token=${encodeURI(JSON.stringify(tokenParams))}`;Copy the code
    1. iOSThe system jumpURLIt’s going to be a problem, and the reason isiOSencodeURIIf the encoding mode is not supported, replace it withencodeURIComponentCan.(Note: after encoding in this way, the place receiving the small program needs to be decoded)
    2. After the jump small program, some circumstances may need to close the current public page, throughaddEventListeneraddlaunchThe event cannot be triggered.
    [dom].addEventListener("launch", function (e) {
        //     console.log("success");
        // });
    Copy the code

    Solution: Dynamic as needed where neededdomaddlanunchEvent, throughinfoA certain parameter is judged to be sufficientlaunchEvent, plus a corresponding callback to execute as needed.

    export function wx_launch(info) { ... + var launchScript = document.createElement("script"); + launchScript.type = "text/javascript"; + if (info.needLaunch) { + launchScript.appendChild(document.createTextNode( + `var btn = document.getElementById('launch-btn'); + btn.addEventListener('launch', function (e) {\n + WeixinJSBridge.call('closeWindow'); // info.callback + }); ` +)); + btn.appendChild(launchScript) + } - btn.addEventListener("launch", function (e) { - console.log("success"); -});Copy the code

    Note:WeixinJSBridge.call('closeWindow')Close the current browser and return to the chat window of the official account.It only works in wechat browser.

reference

  • Official wechat document
  • Appellate-wx-open-launch-appellate (VUE dynamic Generation)

More quality articles

  • HXDM front-end development specification arrangement
  • Product: I want a date and time selection interface like this!!
  • How much do YOU know about JS communication? JS and multiterminal application communication
  • ES6 Common but ignored methods (async)
  • ES6 commonly used but overlooked methods (fourth bullet Proxy and Reflect)
  • Common but overlooked methods for ES6 (Destruct assignments and values first)
  • Take a look at the most fully written implementation of ES6 Promise

“Likes, favorites and comments”

❤️ follow + like + favorites + comments + forward ❤️, original is not easy, encourage the author to create a better article, thank 🙏 everyone.