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

in 默认分类 with 1 comment

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

在Vue3使用

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

<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#L4scriptstyle标签进行了拦截

这里可以通过 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应该如下

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初始化失败的情况下阻止了下方的事件。

Responses
  1. 使用script和style标签的地方,我使用v-is代替了,但是不管用是为什么?

    Reply