MonikaCeng
MonikaCeng
  • 发布:2021-03-17 13:00
  • 更新:2021-03-17 13:08
  • 阅读:2119

uni-app纯webview项目代码示例,包括返回按钮的处理以及user-agent的更改

分类:nvue

这个方法需要nvue,你可以新建项目时,把默认的index.vue改成index.nvue,然后用下面的代码全部覆盖

<script>  
	export default {  
		onLoad() {  
			const url = 'https://tools.qvdd.cn/request-headers' // 改成你自己的链接  
			const uaAppend = 'your_ua_content' // 改成你自己的ua  
			plus.navigator.setUserAgent(plus.navigator.getUserAgent() + ' ' + uaAppend)  
			const sysInfo = uni.getSystemInfoSync()  
			const styles = { // https://www.html5plus.org/doc/zh_cn/webview.html#plus.webview.WebviewStyles  
				width: sysInfo.safeArea.width,  
				top: sysInfo.statusBarHeight,  
				bottom: 0,  
				scalable: true, // 默认不能缩放,在访问PC页面时体验不好  
				errorPage: '/hybrid/html/error.html', // 网页打不开时打开这个页面  
				cachemode: 'cacheElseNetwork' // 默认是 default  
			}  
			const wv = plus.webview.open(url, 'id', styles)  
			plus.key.addEventListener('backbutton', ()=>{  
				wv.canBack((e)=>{  
					if (e.canBack) {  
						wv.back()  
					} else {  
						uni.showModal({  
							title: '是否退出App?',  
							success: (res) => {  
								if (res.confirm) {  
									plus.runtime.quit()  
								}  
							}  
						})  
					}  
				})  
			})  
		}  
	}  
</script>

其中的/hybrid/html/error.html可以自己放个漂亮的404模板,我是简单这样写的:

<!DOCTYPE html>  
<html>  
	<head>  
		<meta charset="utf-8" />  
		<meta name="viewport" content="width=device-width, initial-scale=1">  
		<title>error</title>  
	</head>  
	<body>  
		<div style="padding: 15px;">  
			网页打开失败  
		</div>  
	</body>  
</html>

pages.json里设置"navigationStyle": "custom",隐藏顶部标题栏
原文出处:https://coding3.com/archives/uniapp-webview.html

0 关注 分享

要回复文章请先登录注册

MonikaCeng

MonikaCeng (作者)

网页里的图片如何长按保存到相册,还没找到方法,如果你有方案的话,还望赐教
2021-03-17 13:08