手机浏览器或微信中唤起小程序

2024-03-05 00:44

本文主要是介绍手机浏览器或微信中唤起小程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

明文URL Schem唤起小程序

  • 业务需求的场景
  • 使用文档介绍
  • 实现过程
  • 遇到的问题
  • 注意事项
  • 相关文档

业务需求的场景

需要在后台管理系统中的列表数据添加复制功能,复制成功的链接能够在手机浏览器或者微信中打开指定的小程序页面(pages/good/detail/index)

使用文档介绍

需要在手机浏览器或者微信中唤起小程序有两种方式, 小程序URL Scheme文档,开放范围:非个人主体小程序

  1. 通过加密 URL Scheme (需要后端获取加密 Scheme)
  2. 通过明文 URL Scheme (可前端直接拼接)

注意:iOS系统可以直接打开URL Scheme,Android系统需要使用 H5 页面中转

实现过程

当前项目使用的技术是 vite-vue-ts,使用明文 URL Scheme方式唤起小程序
安装项目:pnpm create vite my-project-name --template vue-ts

1.列表页复制按钮事件js,实现生成URL Scheme,并复制到剪切板

const handleClick = ()=>{// URL Scheme需要进入的小程序页面const path = 'pages/good/detail/index'// URL Scheme携带的参数const query = encodeURIComponent(`goodId=${record.goodId}&other=${record.other}`)// 拼接完整的 URL Schemeconst url = encodeURIComponent(`weixin://dl/business/?appid=222222222222&path=${path}&query=${query}`)// 跳转到新增的H5页面的url(看下文),mpAppId公众号id,appId小程序idconst goodUrl = `${location.origin}/good.html?scheme=${url}&mpAppId=11111111111111&appId=222222222222`// 调用后端的接口生成短链接,并复制到剪切板return myRequest(`api/short/url`, { url:goodUrl }).then((resp) => {// 拷贝到剪切板(看下文utils工具)copyText(resp.data)Message.success('复制成功')return resp.data})
}

2.需要在现有的后台管理系统项目新建一个H5页面
在vite.config.ts中配置项build > rollupOptions > input 中新增配置项 good:

export default defineConfig({// ... 其他配置build:{rollupOptions:{// ... 其他配置input: {good: path.resolve(__dirname, 'good.html'), // 新建H5index: path.resolve(__dirname, 'index.html'), // 原系统入口页},output: {dir: path.resolve(__dirname, './dist'), // 打包输出问价},}}
})

在vite.config.ts同级目录下新建good.html文件,并引入小程序微信开放标签JDK的js文件

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><linkrel="icon"type="image/svg+xml"href="/logo.png"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>跳转中...</title>// 小程序微信开放标签<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script></head><body><div id="app"></div><scripttype="module"src="/src/good.ts"></script></body>
</html>

在src下新建good.ts,挂载页面

import { createApp } from 'vue'
import Auth from './Login.vue'
import './themes/login.less'
createApp(Auth).mount('#app')

在src下新建good.vue页面(H5页面),用来跳转小程序(访问复制出来的URL会进入这个页面,然后在点击进入小程序)

<!-- eslint-disable vue/no-lone-template -->
<template><div class="good">// 手机浏览器网页直接打开上文复制出来的url<divv-if="isWeiXin ? false : isMobile"class="public-web-container"><ahref="javascript:"class="public-web-jump-button"@click="openWxApp()">打开小程序</a></div>// 微信中需要使用微信开发标签<divv-show="isWeiXin"id="weChat-web-container"class="weChat-web-container"><wx-open-launch-weappid="launch-btn"class="wx-open-launch-weapp":appid="appId":path="weappPath"><component:is="'script'"type="text/wxtag-template"><button style="width: 200px; height: 45px; text-align: center; font-size: 17px; display: block; margin: 0 auto; padding: 8px 24px; border: none; border-radius: 4px; background-color: #07c160; color: #fff">打开小程序</button></component></wx-open-launch-weapp></div>// 桌面端提示用手机网页<divv-if="isDesktop"class="desktop-web-container"><p>请使用手机打开网页</p></div></div>
</template>
<script lang="ts" setup>
// 开放标签获取签名(签名需要后端生成)
const getSign = (params: { url: string })=>{return axios.get(`/api/get/sign?url=${params.url}`)
}const isWeiXin = ref<boolean>(false)
const isMobile = ref<boolean>(false)
const isDesktop = ref<boolean>(false)
// mpAppId 公众号id,  appId 小程序id
const { mpAppId = '11111111111111', appId = '222222222222', scheme } = Object.fromEntries(new URLSearchParams(location.search))
const weappPath = ref('')const errorCb= (e: any) => {console.error('错误原因:', e.detail.errMsg)
}onMounted(() => {// 微信页面需要注册开放标签document.addEventListener('WeixinOpenTagsError', errorCb)if (isWeiXin.value) {getSign({ url: encodeURIComponent(location.href.split('#')[0]) }).then((res) => {const { data } = res.data;(window as any).wx.config({debug: false,appId: mpAppId,timestamp: data.timestamp,nonceStr: data.noncestr,signature: data.sign,jsApiList: ['uploadImage'],openTagList: ['wx-open-launch-weapp'],})})}
})onUnmounted(() => document.removeEventListener('WeixinOpenTagsError', errorCb))onBeforeMount(() => {const params = new URLSearchParams(scheme)const query = params.get('query') as stringweappPath.value = `${params.get('path')}?${query}`// 区分平台const ua: any = navigator.userAgent.toLowerCase()const isWXWork = ua.match(/wxwork/i) === 'wxwork'isWeiXin.value = !isWXWork && ua.match(/micromessenger/i) == 'micromessenger'if (navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|IEMobile)/i)) {isMobile.value = true} else {isDesktop.value = true}
})const openWxApp = () => {// 非微信中网页location.href = decodeURIComponent(scheme)
}
</script><style lang="less" scoped>
* {padding: 0;margin: 0;
}
.good{position: absolute;top: 0;bottom: 0;left: 0;right: 0;
}
.weChat-web-container,
.public-web-container,
.desktop-web-container {display: flex;flex-direction: column;align-items: center;
}
.wx-open-launch-weapp {position: absolute;bottom: 50%;left: 0;right: 0;display: flex;flex-direction: column;align-items: center;transform: translateY(-50%);
}
.public-web-jump-button {position: absolute;bottom: 50%;transform: translateY(-50%);display: inline-block;width: 184px;margin-left: auto;margin-right: auto;padding: 8px 24px;box-sizing: border-box;background-color: #06ae56;color: #fff;font-weight: 700;font-size: 17px;text-align: center;text-decoration: none;line-height: 1.41176471;border-radius: 4px;overflow: hidden;-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.desktop-web-container p {position: absolute;top: 50%;transform: translateY(-50%);
}
</style>

src > utils > index 工具文件

 // 复制剪切板功能
function fallbackCopyTextToClipboard(text: string) {let textArea = document.createElement('textarea')textArea.value = text// Avoid scrolling to bottomtextArea.style.top = '0'textArea.style.left = '0'textArea.style.position = 'fixed'document.body.appendChild(textArea)textArea.focus()textArea.select()return new Promise<boolean>((resolve, reject) => {try {let successful = document.execCommand('copy')resolve(successful)} catch (err) {reject(err)} finally {document.body.removeChild(textArea)}})
}export  const copyText = (text: string): Promise<boolean> => {if (!navigator.clipboard) {return fallbackCopyTextToClipboard(text)}return navigator.clipboard.writeText(text).then(() => true)
}

遇到的问题

  1. 链接没有加密,打开网页是空白的,使用encodeURIComponent解决
  2. 链接过长,打开网页是空白的,通过后端生成短链接解决
  3. 注册开放标签注册失败,也会导致网页是空白的

注意事项

  1. 一定要配置 :在MP平台->设置->隐私与安全->明文Scheme拉起此小程序声明
  2. 微信开发标签一定要配置:登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。

相关文档

链接: URL Scheme文档
链接: 获取短链接
链接: 开放标签

这篇关于手机浏览器或微信中唤起小程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/774792

相关文章

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

python编写朋克风格的天气查询程序

《python编写朋克风格的天气查询程序》这篇文章主要为大家详细介绍了一个基于Python的桌面应用程序,使用了tkinter库来创建图形用户界面并通过requests库调用Open-MeteoAPI... 目录工具介绍工具使用说明python脚本内容如何运行脚本工具介绍这个天气查询工具是一个基于 Pyt

Ubuntu设置程序开机自启动的操作步骤

《Ubuntu设置程序开机自启动的操作步骤》在部署程序到边缘端时,我们总希望可以通电即启动我们写好的程序,本篇博客用以记录如何在ubuntu开机执行某条命令或者某个可执行程序,需要的朋友可以参考下... 目录1、概述2、图形界面设置3、设置为Systemd服务1、概述测试环境:Ubuntu22.04 带图

Python程序打包exe,单文件和多文件方式

《Python程序打包exe,单文件和多文件方式》:本文主要介绍Python程序打包exe,单文件和多文件方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python 脚本打成exe文件安装Pyinstaller准备一个ico图标打包方式一(适用于文件较少的程

Python程序的文件头部声明小结

《Python程序的文件头部声明小结》在Python文件的顶部声明编码通常是必须的,尤其是在处理非ASCII字符时,下面就来介绍一下两种头部文件声明,具有一定的参考价值,感兴趣的可以了解一下... 目录一、# coding=utf-8二、#!/usr/bin/env python三、运行Python程序四、

如何基于Python开发一个微信自动化工具

《如何基于Python开发一个微信自动化工具》在当今数字化办公场景中,自动化工具已成为提升工作效率的利器,本文将深入剖析一个基于Python的微信自动化工具开发全过程,有需要的小伙伴可以了解下... 目录概述功能全景1. 核心功能模块2. 特色功能效果展示1. 主界面概览2. 定时任务配置3. 操作日志演示

如何关闭Mac的Safari通知? 3招教你关闭Safari浏览器网站通知的技巧

《如何关闭Mac的Safari通知?3招教你关闭Safari浏览器网站通知的技巧》当我们在使用Mac电脑专注做一件事情的时候,总是会被一些消息推送通知所打扰,这时候,我们就希望关闭这些烦人的Mac通... Safari 浏览器的「通知」功能本意是为了方便用户及时获取最新资讯,但很容易被一些网站滥用,导致我们

Redis迷你版微信抢红包实战

《Redis迷你版微信抢红包实战》本文主要介绍了Redis迷你版微信抢红包实战... 目录1 思路分析1.1hCckRX 流程1.2 注意点①拆红包:二倍均值算法②发红包:list③抢红包&记录:hset2 代码实现2.1 拆红包splitRedPacket2.2 发红包sendRedPacket2.3 抢

无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案

《无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案》:本文主要介绍了无法启动此程序,详细内容请阅读本文,希望能对你有所帮助... 在计算机使用过程中,我们经常会遇到一些错误提示,其中之一就是"api-ms-win-core-path-l1-1-0.dll丢失

SpringBoot后端实现小程序微信登录功能实现

《SpringBoot后端实现小程序微信登录功能实现》微信小程序登录是开发者通过微信提供的身份验证机制,获取用户唯一标识(openid)和会话密钥(session_key)的过程,这篇文章给大家介绍S... 目录SpringBoot实现微信小程序登录简介SpringBoot后端实现微信登录SpringBoo