常见问题
小程序webview嵌入,文件无法预览
由于iOS微信小程序webview中,window.open无法调起微信自带的预览功能,需要通过中间页的形式,借助微信原生页面进行文件预览
- 创建文件预览中间页
在现有微信小程序项目下创建文件预览中间页(比如/pages/file/file)
wxml内容可以是提示加载中的文案,例如:
<!--新增文件预览中间页-->
<text>文件加载中...</text>js内容处理文件的下载和预览
// 新增文件预览中间页
Page({
onLoad(options) {
const url = decodeURIComponent(options.url); // 解析路径中的url参数
const name = decodeURIComponent(options.name); // 解析路径中的name参数
console.log(url, name);
// 下载文件
wx.downloadFile({
url,
async success({ tempFilePath }) {
await wx.navigateBack(); // 回到webview页面
wx.openDocument({
filePath: tempFilePath,
}); // 文件预览
},
fail(error) {
console.error(error);
wx.showToast({
title: '预览文件失败',
})
}
});
},
})- 修改webview页面中webview组件的src链接,添加参数downloadPageUrl
downloadPageUrl是刚刚添加的微信小程序文件预览中间页的路径,需要进行encodeURIComponent处理,以下代码以/pages/file/file为例,encodeURIComponent('/pages/file/file')后得到%2Fpages%2Ffile%2Ffile
<view>
<web-view src="[https://qiyukf.com/client?k=xxx&wp=1&downloadPageUrl=%2Fpages%2Ffile%2Ffile](https://qiyukf.com/client?k=xxx&wp=1&downloadPageUrl=%2Fpages%2Ffile%2Ffile)"></web-view>
</view>- 修改完成,测试效果
- 由于加载七鱼web页面时,传入了参数downloadPageUrl,七鱼web页面会记录这个微信小程序文件预览中间页地址
- 访客端点击文件时,七鱼web页面调用微信内部方法,打开上一步记录的文件预览中间页,并拼接好url和name参数(/pages/file/file?url=下载链接&name=文件名)
- 由于第1步创建的js文件在页面加载时解析和处理了url参数,会执行文件下载、预览动作。由于navigateBack销毁了中间页,在关闭预览后,用户会直接回到webview页面
效果如下:
这篇文档有帮助吗?