文章目录

  • 前言
  • 一、webview内嵌网页的授权认证
    • 1.内嵌页面
    • 2.登录页面
  • 二、web端相关函数
    • 1.判断是否是小程序环境

前言

随着微信小程序的广泛应用,小程序的用户越来越多,但受其小程序体积限制的影响,不能够完全满足用户的要求,应运而生的web-view组件很好的解决的这一问题。

web-view主要是内嵌H5网站页面又以下几个优点:

  • 内嵌web-view能够直接运行在小程序中,大大减少了用户的开发成本
  • 能够实现小程序与h5的跳转,有良好的扩展性,方便用户多端间引流

小程序相关API

属性 类型 默认值 必填 说明 最低版本
src string webview 指向网页的链接。可打开关联的公众号的文章,其它网页需登录小程序管理后台配置业务域名。 1.6.4
bindmessage eventhandler 网页向小程序 postMessage 时,会在特定时机(小程序后退、组件销毁、分享)触发并收到消息。e.detail = { data },data是多次 postMessage 的参数组成的数组 1.6.4
bindload eventhandler 网页加载成功时候触发此事件。e.detail = { src } 1.6.4
binderror eventhandler 网页加载失败的时候触发此事件。e.detail = { url, fullUrl },其中 fullUrl 为加载失败时的完整 url 1.6.4

一、webview内嵌网页的授权认证

1.内嵌页面

// miniprogram/pages/2.18/web-view/index.js
Page({/*** 页面的初始数据*/data: {url:'',webViewData:{}},onReceivedMessage(e){let data = e.detail.data// data可能是多次 postMessage 的参数组成的数组if (Array.isArray(data)) data = data[0]console.log('onReceivedMessage',JSON.parse(data));this.setData({webViewData:JSON.parse(data)})},onShareAppMessage(options) {console.log('title',this.data.webViewData.title);console.log('webViewUrl',options.webViewUrl)return {title: this.data.webViewData.title,path: `/web-view/index?web-view-url=${options.webViewUrl}`}},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {let token = getApp().globalData.tokenlet url = `http://localhost:3000/user/web-view?token=${token}`console.log('token', token);this.setData({url})},
})
<web-view bindmessage="onReceivedMessage" src="{{url}}" style="z-index:-1"></web-view>

2.登录页面

Page({/*** 页面的初始数据*/data: {},onShareAppMessage:function(options) {console.log('分享')return {title: '登陆',path: '/pages/index'}},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {// wx.showShareMenu({//   withShareTicket: true// })},
})
<view class="page-section"><text class="page-section__title">微信登陆</text><view class="btn-area"><button bindgetuserinfo="login" open-type="getUserInfo" type="primary">登陆</button><navigator style="padding-top:20rpx;" url="/web-view/index" open-type="navigate">web view</navigator><button open-type="share" type="primary">分享</button></view>
</view>

二、web端相关函数

1.判断是否是小程序环境

<!DOCTYPE html>
<html><head><title>{{title}}</title><script type="text/javascript" src="/static/js/jweixin-1.6.0.js"></script><script type="text/javascript" src="/static/js/jquery.js"></script><script type="text/javascript" src="/static/js/jquery.cookie.js"></script><style>* {font-size: 24px;}</style>
</head><body><h1>{{title}}</h1>{{if title}}<p>has title.</p>{{/if}}<p>{{each title $value $index}}<span>{{$index}}:{{$value}}</span>{{/each}}</p><p>{{each arr }}<span>{{$index}}:{{$value}}</span>{{/each}}</p><p>{{now | dateFormat "yyyy-MM-dd hh:mm:ss"}}</p><p>Art-Template Welcome to {{title}}</p><input id="name" value="ly" /><br /><br /><input id="send-btn" type="button" value="send"></input><p id="output"></p><input id="share-btn" type="button" value="share" style="width: 100px;height:30px;border:solid 1px grey;"></input><script type="text/javascript">// 当处于小程序内document.addEventListener('intoMiniprogram', () => {retrieveHomeData()}, false)// 检查是不是位于小程序内let isInMiniprogram = falsefunction changeIsInMiniprogramState() {if (!isInMiniprogram) {isInMiniprogram = true$.cookie("isInMiniprogram", true)document.dispatchEvent(new Event('intoMiniprogram'))console.log('isInMiniprogram', isInMiniprogram);}}if (/token=\d+/.test(window.location.search)) {changeIsInMiniprogramState()} else if ( /miniProgram/.test(navigator.userAgent) ){changeIsInMiniprogramState()}else if (($.cookie("isInMiniprogram") || '') == 'true') {changeIsInMiniprogramState()} else {function onWeixinJSBridgeReady() {if (window.__wxjs_environment === 'miniprogram'){changeIsInMiniprogramState()}}if (!window.WeixinJSBridge || !WeixinJSBridge.invoke) {document.addEventListener('WeixinJSBridgeReady', onWeixinJSBridgeReady, false)} else {onWeixinJSBridgeReady()}}// retrieveHomeData()// 在小程序中,模拟调用接口function retrieveHomeData() {$('#send-btn').bind('click', (e) => {let name = $('#name').val()console.log('name', name);let authorization = $.cookie("Authorization") || ''$.ajax({url: `http://localhost:3000/user/home?name=${name}`,method: 'get',headers: {'Authorization': authorization},success(res) {console.log('res', res)$("#output").text(JSON.stringify(res))},fail(err) {$("#output").text(err)}})})$('#share-btn').bind('click', (e) => {console.log('share btn click')wx.miniProgram.postMessage({data: JSON.stringify({action: 'share',title: window.document.title})});// wx.miniProgram.navigateBack()})}</script><script type="text/javascript" src="/static/js/vconsole.min.js"></script><script>// 初始化var vConsole = new VConsole();console.log('Hello world');</script>
</body>
</html>

接口端

// 一个web-view页面,是给小程序加载的
router.all('/web-view', async function (ctx) {let token = ctx.request.query.tokenctx.session.sessionKeyRecordId = ~~ctx.session.sessionKeyRecordId + 1if (token) ctx.cookies.set('Authorization', `Bearer ${token}`, { httpOnly: false });let title = 'web view from koa' + ctx.session.sessionKeyRecordIdawait ctx.render('index', {title,arr: [1, 2, 3],now: new Date()})
});

【愚公系列】2022年09月 微信小程序-webview内嵌网页的授权认证相关推荐

  1. [微信小程序]WebView内嵌H5实现本地文件上传

    [官方文档] 小程序与H5如何互相跳转 小程序与H5交互以上传文件为例 微信小程序开放能力web-view使用之h5页面与小程序页面交互传值 快速小程序开发之微信小程序内嵌 H5 微信小程序web-v ...

  2. 微信小程序与内嵌网页交互实现支付功能

    上个月,小程序开放了新功能,支持内嵌网页,所以我就开始了小程序内嵌网页之路,之前我只是个小安卓. 内嵌网页中可使用JSSDK 1.3.0提供的接口,可坑就来了,居然不支持支付接口的调用,经过一番研究, ...

  3. 实现微信小程序web-view内嵌H5中的下载功能(大文件切片下载)

    实现微信小程序内嵌H5中的下载功能 一.项目场景: 难点 解决方案: 1.H5微信小程序: a.首先必不可少的是安装jweixin-module模块: b.在main.js中将依赖绑定: c.H5对应 ...

  4. 微信小程序webview内嵌H5页面缓存

    微信小程序webview内嵌H5页面缓存 参考链接: link. 问题描述: 公司项目已经开发了一个移动端的vue项目,以微信小程序作为一个入口,节省资源去原生开发,webview成了最好的选择.vu ...

  5. 【愚公系列】2022年09月 微信小程序-微信小程序实现网页一键登录功能

    文章目录 前言 一.微信小程序实现网页一键登录功能 1.旧版登录方法 2.新版登录方法 二.相关第三方包源码 前言 如果微信小程序要获取微信登录的用户信息,需要拿到code去后台换取用户信息,具体步骤 ...

  6. 【愚公系列】2022年09月 微信小程序-图片加载和全屏适配问题

    文章目录 前言 一.图片加载 二.适配机型实现全屏背景图 前言 在使用图片问题中可能会遇到各种各样的问题,比如图片加载不出来,图片显示在不同机型效果不同,图片加载展示问题等等. 微信小程序image相 ...

  7. 【愚公系列】2022年09月 微信小程序-自定义导航栏功能的实现

    文章目录 前言 一.自定义导航栏功能的实现 1.组件的封装 2.使用 前言 导航栏是指位于页面顶部或者侧边区域的,在页眉横幅图片上边或下边的一排水平导航按钮,它起着链接站点或者软件内的各个页面的作用. ...

  8. 【愚公系列】2022年11月 微信小程序-优购电商项目-授权页面

    文章目录 前言 1. 授权页面 一.授权页面 1.业务逻辑 2.涉及的接口数据 二.授权页面相关代码 1.页面代码 2.效果 前言 前言:由于微信官方修改了 getUserInfo 接口,所以现在无法 ...

  9. 【愚公系列】2022年09月 微信小程序-Page页面扩展

    文章目录 前言 一.Page页面扩展 1.组件的封装和引用 2.页面使用 3.效果 二.其他相关封装 1.pop-up组件 2.LoginPanel组件 3.LoginPanel组件 前言 在小程序日 ...

最新文章

  1. 仅凭一部iPhone手机,打造现实版元宇宙
  2. ora00600内部错误代码oracle,ORA-00600: 内部错误代码, 参数: [13013]
  3. GDCM:获取序列超声的测试程序
  4. 棋牌游戏服务器架构: 总体设计
  5. python中构造方法可以被继承吗_python – 类继承:构造函数应该兼容吗?多重继承的情况?...
  6. 【BZOJ3930】选数(莫比乌斯反演倍数形式,杜教筛)
  7. click事件在什么时候出发_剖析setTimeout和click点击事件的触发顺序
  8. SQL 创建数据库、表以及索引
  9. IDEA 点击进入方法内部_Idea中,听说会了Debug,你就离大佬不远了!
  10. 【报告分享】2020中国教育行业生存实录.pdf(附下载链接)
  11. 退出登入的php怎么写,php中退出登录怎么写
  12. vs2019 product key
  13. 无法访问srv解析_访问本地项目,php不被解析,出现文件下载
  14. bulkwrite 批量插入_使用EF扩展EntityFramework.BulkInsert实现批量插入
  15. Java实现文件下载Zip压缩
  16. ffmpeg将amr格式转成mp3格式
  17. 【ECLIPSE 二】eclipse java web 版本修改问题 3.0-2.5
  18. 中国龙与西方龙的区别
  19. 锐龙r7 PRO 4700G、锐龙r5 PRO 4400G和锐龙r3 4200G 的区别
  20. Android实现拍照相册图片上传功能

热门文章

  1. Jquery(八)插播:jQuery实施方案
  2. 如何使用Django显示来自DigitalOcean API的数据
  3. jquery图片播放浏览插件prettyPhoto
  4. 美国确诊超100万!教你用Python画出全球疫情动态图
  5. 从三层架构说起,谈谈对历史项目的小改造
  6. android 应用对内存是如何限制的?我们应该如何合理使用内存?如何限制的?
  7. 深入了解JavaScript 中的For循环之详解
  8. 山东ISO9001质量管理体系需准备哪些资料
  9. 【解决方案】AI+视频监控, EasyCVR如何赋能智慧平安社区建设?
  10. 去掉Android开机无SIM卡提示框