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.12
And above - The system version must be:
IOS 10.3
And above,The Android 5.0
And 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
-
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”.
-
Importing JS files
- When you need to call
JS
The interface page is introduced as followsJS
Files, (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: Supported
AMD/CMD
Standard module loading method loading
- When you need to call
-
Verify the configuration through the config interface injection permission
- All required
JS-SDK
The page must first inject configuration information, or it will not be calledurl
It only needs to be called once, for changesurl
的SPA
的web app
In every timeurl
Change when called at presentAndroid
Wechat client is not supportedpushState
的H5
New feature, so usepushState
To implement theweb app
The page will cause the signature to failAndroid6.2
Repair).
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
- All required
-
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
-
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
-
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
- Label error
- Solution: In
main.js
Add the following code to;
// main.js
Vue.config.ignoredElements = ['wx-open-launch-weapp'];
Copy the code
wx-open-launch-weapp
In theDom
Don’t show
- The current
wx-open-launch-weapp
In the tagDom
Only 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-weapp
Content control, style debugging and so on are difficult, and rendering data is troublesome.
wx-open-launch-weapp
In theDom
Display, 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.forVue
Such view frames in order to avoidtemplate
Tag conflict issues can be used<script type="text/wxtag-template"><script>
To replaceTo wrap slot templates and styles.
- 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 one
Dom
When 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-weapp
Write anything in. - After my own try, I gave up in
wx-open-launch-weapp
Write 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 generate
wx-open-launch-weapp
- 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
- 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
- Dynamically generated
wx-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
- 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
- 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.12
And above - Through the above questions, we can modify
is_version
Method, first judge the large version number and the first greater than7
Return directly whentrue
When is equal to the7
, determine whether the second is greater than0
, is more than0
Direct returntrue
Is equal to0
Is 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 calls
split
Method after the number in the array is a string.
- Modify dynamic generation
wx-open-launch-weapp
methods
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
- call
wx_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 handling
4
I have encountered all these problems.wx-open-launch-weapp
In the content display style problem and card data can not dynamically render problems, dynamic generationwx-open-launch-weapp
的Dom
I 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
URL
Jump applet with parameters, applet receive incomplete, jumpURL
As follows:
What the applet receives is
"Source=public&token={"
The reason is thattoken
Is an object passed throughJSON.stringify
Generated string,URL
An insert generated from a template stringtoken
Generated, causing the applet to receive the truncated quotes, so we need to use them in the generated object type stringencodeURI
forURL
Encoding.const pathStr = 'pages/detail/speakingDetail.html? Source=public'; let tokenParams = {}; const miniProgramUrl = `${pathStr}&token=${encodeURI(JSON.stringify(tokenParams))}`;Copy the code
iOS
The system jumpURL
It’s going to be a problem, and the reason isiOS
对encodeURI
If the encoding mode is not supported, replace it withencodeURIComponent
Can.(Note: after encoding in this way, the place receiving the small program needs to be decoded)- After the jump small program, some circumstances may need to close the current public page, through
addEventListener
addlaunch
The event cannot be triggered.
[dom].addEventListener("launch", function (e) { // console.log("success"); // }); Copy the code
Solution: Dynamic as needed where needed
dom
addlanunch
Event, throughinfo
A certain parameter is judged to be sufficientlaunch
Event, 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.