Author: qiuwww

  1. Your business may need h5 embedded in the small program, as well as the setting of sharing, and some points of attention;
  2. Personal small program development experience summary;

🖇 Development related

1, use,web-viewLoading H5 is shared with the applet that sets up the current page

Web – the view document

The small programweb-viewThe same as the general iframe

Similarities:

  1. Are used to load dynamic resources online, such as HTML, PDFS,web-viewIframe is an HTML file used to load a new dynamic resource in a web page.

Places of difference

  1. Small programweb-viewThe restrictions are strict:
    1. web-viewYou need to configure the domain name whitelist in the background for the loaded URL, including other urls embedded in the internal iframe.
      1. The small program limits the loading of resources are HTTPS requests, so sometimes there is no loading out of the problem, is likely to be the interface or page address problems;
      2. Another problem is that it is best not to use development debug mode when testing on the real machine. You may miss some problems.
  2. web-viewWill automatically spread the entire small program page, and the default display to the top layer, can not be overwritten;
  3. The small program endweb-viewThe component must have a native navigation bar, and the underside must be full screenweb-viewComponents,navigationStyle: custom 对 web-viewThe component is invalid.
  4. Small program cannot obtainweb-viewObjects, that is, completely isolated from each other, cannot be manipulated by obtaining component references;
    1. The embeddedweb-viewWeb pages can onlypostMessageFor applets, and applets can only be used inA message is triggered and received at a specific time (applet back, component destroy, share). That is, the message is not in real time, it’s stored in an array and it gets picked up at all of these times,web-viewThe messages are going to keep accumulating, so this array is going to keep getting bigger;
    2. bindload“, the method developer tool is invalid, and when tested,As long as the address format is correct, it is considered a success and will be triggeredIs not triggered when the page is fully loaded;
    3. binderror, the method developer tool is invalid,If the address format is incorrect, the load failsIt will not trigger if it is not loaded;

web-viewLoad the H5 page

  1. You need to render when the URL is retrievedweb-viewComponent, otherwise a blank page may appear;
<template>
  <view class="common-webview">
    <web-view v-if="url" class="web" :src="url" @message="onWebMessage" />
  </view>
</template>
Copy the code
  1. @messageTo accept the message issued by the page, need to introduce the SDK of wechat embedded small program, and then usewx.miniProgram.postMessage({ data: 'foo' })To send a message;
  2. web-view, embedded H5 needs to open the small program page can call the jump method of the small program to jump, here note that the TAB page can only be usedwx.miniProgram.switchTab, to jump.
(window as any).wx.miniProgram.navigateTo({
  url: `/pages/common/webview? url=The ${encodeURIComponent(resolveH5Url)}`
});
Copy the code

web-viewPage sharing Settings

  1. The most intuitive way is to open the mini program page, and pass the shared title and picture, as follows:
    1. This is mainly for some H5 code can not be modified, or load a group of H5 page share title does not change, for the need to constantly switch to share content, is not possible;
/ / use in h5 wx. MiniProgram. NavigateTo
wx.navigateTo({
  url: `/pages/common/webview? url=The ${encodeURIComponent(jumpUrl)}&imageUrl=${imageUrl}&title=${title}`
});
Copy the code
  1. For their own controllable H5 pages, you can usepostMessage, the parameters to be shared will be dynamically sent to the applet page, so that the applet page through the current URL to match the message object here, so as to get the shared information, the specific operation is as follows:
/ / h5 operations
if (env.inWechatMiniProgram) {
  (window as any).wx.miniProgram.postMessage({
    data: {
      title: title || ' '.// Share the title
      imageUrl: imageUrl || ' '.// Share the display picture
      pageUrl: window.location.href, // The url of the current page, which needs to be used as the key to identify the message}}); }// Small program side
// When we click share, we call onShareAppMessage and onWebMessage (first).
// Accept the postMsg message list, which will be sent when the page is entered or the action is clicked. This will be called when the share button of the applet is clicked, before onShareAppMessage
async onWebMessage({ detail: message }) {
  this.messageList = message.data || [];
}

// Click the share button and the current function is called
async onShareAppMessage(options = {}) {
  const { webViewUrl } = options;
  const searchCurOptions = this.messageList.reverse().find(item= > item.pageUrl === webViewUrl) || {};
  console.log("Here is the information currently shared.", searchCurOptions)
}
Copy the code

More configuration is required, which can be achieved by adding parameters.

2. Page mode and title bar return

Page mode

Page development Mode

You can customize the navigation bar by setting the navigationStyle of the page in pages. Json to custom.

  1. Default, default mode not set, normal page operation process;
  2. Custom navigation, usually used for home page display or custom title bar, but forweb-viewInvalid page;

Title bar return problem

Because small programs will only jump between small program pages, the default title bar will appear the back button, so if you embed h5 in the tabbar page, the h5 internal jump is not allowed to appear the back button, so we need special treatment:

  1. If the first opened is a page embedded with H5, the jump of the current page needs to call the small program interface to jump;
  2. When the page after the back button appears, you do not need to use it;
wx.miniProgram.navigateTo({
  url: `/pages/common/webview? url=The ${encodeURIComponent(jumpUrl)}&imageUrl=${imageUrl}&title=${title}`
});
Copy the code

3. Subcontracting

Wechat small program subcontracting

Why subcontracting is needed

Wechat client before opening the small program, the code package of the whole small program will be downloaded to the local, this strategy can alleviate the problem of white screen when the page jump. At the same time, wechat also set the small program code package size of 2M (initially only 1M) to ensure that the small program can have a good start speed.

Subcontracting should pay attention to the place

  1. The size of each subcontract of wechat small program is 2M, and the total volume cannot exceed 20M in total;
  2. Try to keep the main package to load only the necessary content, mainly including some required public resources /JS scripts, tabBar pages, preferably only these pages;
  3. The earlier you subcontract, the better, if the later subcontracting, otherwise the later subcontracting, it is necessary to deal with the address called by internal and external in the early;
    1. You can’t change pages that are already out there;
    2. The page can not be redirected through the route, that is, the route and the page location is absolutely corresponding;
  4. The main package may not reference the contents of a subpackage.Subpackages can only reference contents within their own package and within the main package, subpackages cannot be nested in subpackages;
    1. Independent subcontracting is a special type of subcontracting in small programs that can operate independently of the main package and other subcontracting. There is no need to download the main package when entering the applet from the standalone subpackage page. The main package is only downloaded when the user enters the normal subpackage or the inside page of the main package, which we don’t usually use.
  5. Subpackage pre-download: Developers can configure the framework to automatically pre-download possible subpackages when entering a page of a small program, improving the startup speed when entering subsequent subpackage pages. For independent subcontracting, it is also possible to pre-download the main package.

4, small program development configuration condition

Uni – app setting condition

Startup mode configuration, which takes effect only during development, is used to simulate a direct page scenario, such as: after the small program is forwarded, the user clicks the opened page.

You can also ensure that the selected compilation mode works every time the applet is refreshed. You can also ensure that the selected compilation mode works every time the applet is refreshed.

{
  "condition": {
    "current": 0."list": [{"name": "index"."path": "pages/index/index"."query": "isShowHelp=1"}}}]Copy the code

5. Some rules of jump between small program and H5 and small program

  1. Small program sharing, can only be small program open;
  2. Public share can only be open public account;
  3. Small program throughweb-view, h5 can be turned on;
  4. Small program jump small program is no restrictions, as long as you know the other side of the APPID and jump to the target page, can also set the jump isExperience version/development version/official version.
    1. Only the official version can change to the official version.
  5. H5 open small program, H5 needs to introduce wechat SDK, set the calling function, and then jump through open label;
  6. Small program can not jump public number, but can useofficial-accountComponent concerns associated with the public account;
  7. Open the App. When the applet is opened from the scene where the App is opened (scene value 1069), the applet will gain the ability to return to the App. At this point, the user can click the button to open the App that pulls up the applet. The small program can not open any APP, can only jump back to the APP.
<script>
  // Applet jumps to applet
  wx.navigateToMiniProgram({
    appId: appid, // AppID of the peer applet
    path: path, // The address of the target page can be spelled directly in path. The later part will become query
    extraData: {
      // The data to be passed to the target applet
      foo: 'bar'
    },
    envVersion: 'release'.// The version of the applet to open. This parameter is valid only when the current applette is a development or experience version. If the current applet is an official version, then the open applet must be an official version.
    success(res) {
      // Open the successful subsequent operation, such as bury something
      // wxTelescope(baseKey + '-skip');}});</script>

<! -- h5 Jump applet -->
<script>
  // Needs to be configured
  wx.config({
    openTagList: ['wx-open-launch-weapp']});</script>
<! -- Jump button -->
<wx-open-launch-weapp
  class="launch-btn"
  :username="tagUsername"
  :path="tagPath"
  @error="handleErrorFn"
  @launch="handleLaunchFn"
>
  <script type="text/wxtag-template">
    <div style="padding: 10000px">The jump button</div>
  </script>
</wx-open-launch-weapp>
Copy the code

🖇 on pit

1. Channel parameter processing

Applet life cycle – Hot start/cold start and its related parameters

Small program running mechanism

  • Cold start: If the user opens it for the first time, or the small program is destroyed and opened again by the user, then the small program needs to reload and start, namely cold start.
  • Hot start: If the user has opened a small program, and then open the small program again within a certain period of time, the small program is not destroyed, but from the background state into the foreground state, this process is hot start.
    • Common such as, after the startup, scan the code to reopen a page, or click the configuration of the public number navigation;

Differences in parameter obtaining methods

  1. wx.getLaunchOptionsSync
    1. Gets the parameters when the applet starts. withApp.onLaunchIs consistent with the callback parameters.
    2. The parameters you get are those you get when you start cold. No matter where you come from, the data is the same without killing the process.
  2. wx.getEnterOptionsSync.Gets the parameters when the applet starts.
    1. If the current is cold start, return the value andApp.onLaunchIs consistent with wx.getLaunchOptionsSync;
    2. If the current is hot start, the return value is the same as app. onShow;
    3. Therefore, we can keep the parameters obtained each time consistent with the current startup parameters, and hot-start parameters can override the parameters of the same name.
  3. When the small program is destroyed, the two parameters can not get the desired value, so for the small program into the background, if it is not necessary to take the initiative to close, to avoid placing a period of time, open again caused by parameter errors;
    1. When the small program into the background, can maintain a short period of time running state, if this period of time did not enter the foreground, the small program will be destroyed.
    2. When small programs occupy too many system resources, they may be destroyed by the system or actively reclaimed by the wechat client.

Channel setup and acquisition

// Set channel, similar to the general parameters, you can modify the small program background experience code to control the open parameters, simulate channel release

// pages/index/index? channel=3UAKHCEV

// Get the current channel. You can mask or replace it for different parameters
export const getChannel = () = > {
  const { query } = wx.getEnterOptionsSync();
  const { channel } = query;
  return channel;
};
Copy the code

2. Too long scene parameters of small program generated by wechat

Small program QR code scene parameters are limited to 32 characters in length, but there may be a lot of parameters need to be passed in the actual development, such as Pages /common/ webView? url=https%3A%2F%2Fstatic.qa.91jkys.com%2Ff2e%2Fcustomer-h5-im%2F%23%2Fquick-ask%3FcurChannelInDisableList%3D0%26channel% 3D27 can be used only after special treatment. The common methods are as follows:

  1. Middle page + short parameter;
    1. There’s an extra jump;
  2. Short parameter (currently selected scheme);
    1. At present, when entering the page, first judge whether there is a value of scene, if there is, then request the interface to get a complete parameter (json format), and then use this parameter to tune the real business interface;
    2. This way to confirm that the page will be opened;
/ / call
let options = wx.getEnterOptionsSync();
options = await queryLaunchParams(options);

// Method definition: When scanning the two-dimensional code, obtain all parameters in the database through the short parameters of the two-dimensional code
export const queryLaunchParams = async (options = {}) => {
  if (options.scene) {
    const { qrScene } = await store.dispatch('global/getParams', { destScene: options.scene });
    return{... options, ... queryString.parse(qrScene) }; }else {
    returnoptions; }};Copy the code

3,web-viewOpen the PDF file

Can not directly open the PDF online, the detailed steps are as follows

  1. Download files online to local, uni.downloadfile;
  2. Open the downloaded PDF, uni.openDocument, locally

Specific code:

// 1. Download the PDF from the online address, then get the local address, and then use the Web-view to open it
export const getDocumentLocalPath = (url = ' ') = > {
  const types = ['.pdf'];
  const filterArr = types.filter(item= > {
    return url.includes(item);
  });

  if (filterArr.length < 1) {
    return;
  }
  const fileType = filterArr[0];

  return new Promise((resolve, reject) = > {
    wx.downloadFile({
      url,
      success: function(res) {
        const filePath = res.tempFilePath;
        console.log('getDocumentLocalPath', url, filePath);
        wx.openDocument({
          filePath: filePath,
          fileType: fileType.slice(1),
          success: function(res) {
            // Use the PDF local address as the webView address. You need to roll back, otherwise you will have a white page
            uni.navigateBack({
              delta: 1}); resolve(filePath); }}); },fail: function(e) { reject(e); }}); }); };/ / 2. Use
const url = await getDocumentLocalPath(url);
// The webView can open a locally generated address
this.url = url;
Copy the code