微信JS-SDK开放标签使用踩坑

微信的 JS-SDK 提供了在网页上使用开放标签以打开 APP/小程序的能力,但是文档真的是稀烂,记录一下。

在 Vue3 使用

如官方文档的样例,使用开放标签应植入如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

<wx-open-launch-weapp

id="launch-btn"

username="gh_xxxxxxxx"

path="pages/home/index?user=123&action=abc"

>

<script type="text/wxtag-template">

<style>.btn { padding: 12px }</style>

<button class="btn">打开小程序</button>

</script>

</wx-open-launch-weapp>

使用 script 和 style 标签

里面用到了 script 标签,在 vue3 里,script 是不可以直接植入 template 里面的,会报错 VueCompilerError: Tags with side effect (<script> and <style>) are ignored in client component templates. 。

原因是vuejs/vue-next/packages/compiler-dom/src/transforms/ignoreSideEffectTags.ts#L4 对script和style标签进行了拦截

这里可以通过 v-is 进行绕过:使用<div v-is="'script'"></div>以替代<script>。

忽略自定义标签

wx-open-launch-weapp不是一个标准的 html 标签,直接使用虽然也可以但是 vue 会在 console 输出一大堆 warn。

根据文档:

config.ignoredElements Is Now config.isCustomElement

但是当你就这么写入main.js的时候,会发现报 warn The isCustomElement config option is only respected when using the runtime compiler.。因为文档底下的 Important 写着

If config.isCustomElement is assigned to when using a runtime-only build, a warning will be emitted instructing the user to pass the option in the build setup instead;

isCustomElement需要写入 vueCompilerOptions,如果你用的是 vite,你的vite.config.js应该如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

export default defineConfig({

plugins: [

vue({

template: {

compilerOptions: {

isCustomElement: tag => tag === 'wx-open-launch-weapp'

}

}

})

]

})

JS-SDK 初始化成功,verifyOpenTagList 为空

大部分开发应该都是用测试号,在微信开发者工具调试。

但是测试号没有 OpenTag 的权限!……文档没有一处提及,喵喵喵?

直接对接生产账号吧

JS-SDK 在开发者工具初始化成果,在真机初始化失败

一开始看网上经验,jsApiList 不能提供空数组,可以提交['']代替,这样在开发者工具是没有问题的。

但是真机不行(使用的 SDK 版本为 1.6.0)。我的方案是随便申请了一个 jsapi,比如 ['previewImage']

开放标签样式

没做开发以前以为是 sdk 会提取 script 里面的 template 放到 dom 里,后来试了试发现大概原理是微信客户端解析 dom,找到开放标签,由内核渲染里面的 template。

所以页面 css 的样式是不作用于wxtag-template里面的东西的,需要像示例一样写在里面的 style 标签。然后vw vh这种也不能用。

如果需要加载图片,一定需要写绝对路径(带上域名),不然访问的是 localhost。

渲染规则比较奇异,如果需要使用百分比或者vw vh,建议用 js 算完然后给定 px,不要尝试通过wx-open-launch-weapp的 overflow 覆盖掉wxtag-template的元素溢出部分,会有无法理解的现象。

而且如果是非微信客户端,直接就是空白

所以

如果是按钮的场景,建议原本该咋写咋写,然后放一个透明的wx-open-launch-weapp在上面,会省很多事。

可以预先把wx-open-launch-weapp display:none,然后wx.ready再把它显示回来,以免在 sdk 初始化失败的情况下阻止了下方的事件。


微信JS-SDK开放标签使用踩坑
https://hunsh.net/archives/116/
发布于
2021年6月1日
许可协议