uni-app onShareAppMessage里请求数据来自定义标题和图片无效

uni-app onShareAppMessage里请求数据来自定义标题和图片无效

开发环境 版本号 项目创建方式
Mac Mac OS 13.2.1 HBuilderX

产品分类:uniapp/小程序/百度


示例代码:

onShareAppMessage: async () => {
let shareInfo;
try {
let res = await api.reqShare();
shareInfo = {
path: "/pages/index/index",
title: res.title,
imageUrl: res.image,
};
} catch (e) {
shareInfo = {
path: "/pages/index/index",
title: "测试测试测试测试测试",
};
}  
return shareInfo;  
}

操作步骤:

  • 在onShareAppMessage里发起请求,自定义分享内容
  • 点击分享

预期结果:

能够自定义分享

实际结果:

分享出去的是默认内容

bug描述:

我在onShareAppMessage里发起请求, 这样分享出去的内容是默认的标题和图片, 不能自定义:

onShareAppMessage: async () => {
let shareInfo;
try {
let res = await api.reqShare();
shareInfo = {
path: "/pages/index/index",
title: res.title,
imageUrl: res.image,
};
} catch (e) {
shareInfo = {
path: "/pages/index/index",
title: "测试测试测试测试测试",
};
}  
return shareInfo;  
}

更多关于uni-app onShareAppMessage里请求数据来自定义标题和图片无效的实战教程也可以访问 https://www.itying.com/category-93-b0.html

4 回复

不要在分享函数内请求,这里是有时间限制的,建议页面加载完成后先获取到分享封面的标题

更多关于uni-app onShareAppMessage里请求数据来自定义标题和图片无效的实战教程也可以访问 https://www.itying.com/category-93-b0.html


小程序端是可以传入promise参数的,但是必须三秒内响应resolve回传否则还是走默认分享

好的, 感谢

这个问题是因为onShareAppMessage不支持异步操作。在小程序中,分享回调函数需要同步返回分享内容对象,不能等待异步请求完成。

解决方案:

  1. 提前获取分享数据: 在页面加载时就请求分享数据并保存到data中,然后在onShareAppMessage中直接使用这些数据。
data() {
  return {
    shareData: {
      title: '默认标题',
      imageUrl: ''
    }
  }
},
onLoad() {
  this.getShareData();
},
methods: {
  async getShareData() {
    try {
      const res = await api.reqShare();
      this.shareData = {
        title: res.title,
        imageUrl: res.image
      };
    } catch(e) {
      console.error(e);
    }
  }
},
onShareAppMessage() {
  return {
    path: "/pages/index/index",
    title: this.shareData.title,
    imageUrl: this.shareData.imageUrl
  };
}
回到顶部