uniapp webview web-view组件监听网页变化 url变化 与网页通讯

uniapp webview web-view组件监听网页变化 url变化 与网页通讯

需求是在app页面内嵌套自己的h5 或者别人的h5 切换页面时候获取到网页的变化 url的变动

第一种方法就是使用 html5+的方法

javascript 复制代码
//html部分
<web-view :src="webviewPath" class="webview" height="100%" :webview-styles="{width:'100%',height:'100%'}"
			id="webview" ></web-view>
//js部分	
<script>
export default {
onReady() {
// 获取当前Webview窗口对象
			const ws = plus.webview.currentWebview();
			var currentWebview = this.$scope.$getAppWebview()
			setTimeout(() => {
			let wv = currentWebview.children()[0];
			_this.ws.loadURL(_this.webviewPath) //加载h5链接
			// 监听窗口触屏事件
				_this.ws.addEventListener('touchstart', function(e) {
					setTimeout(() => {
						let orderUrl = _this.ws.getURL() //页面链接
						const wsTitle = _this.ws.getTitle() //页面标题
						console.log(_this.ws.getTitle())
						console.log(orderUrl)
						console.log('touchstart');
					}, 100)

				}, false);
				_this.ws.onloaded = () => {
					let orderUrl = _this.ws.getURL()
					console.log('onloaded事件加载完成', orderUrl)
				};
			},1000)//如果是页面初始化调用时,需要延时一下 
}
}
</script>

第二种方法就是使用 html5+的方法 和uniapp的 uni.webview.js

使用uni.webview.js 就可以实现h5和app通讯了,想要h5的任何数据都用通过 uni.webView.postMessage来传递给

app

javascript 复制代码
//html部分
<web-view :src="webviewPath" class="webview" height="100%" :webview-styles="{width:'100%',height:'100%'}"
			id="webview" @message="receiveMsg"></web-view>
	methods: {
			wsEvalJs() {
				// 在webview加载完成后,注入JavaScript代码
				this.ws.evalJSSync(`
				       var script = document.createElement('script');
				       script.src = 'https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js';
				       document.body.appendChild(script);
							 document.addEventListener("UniAppJSBridgeReady", function() {
							   console.log("初始化uniapp的API成功");
								 uni.webView.postMessage({ data: { type: "href",href:window.location.href,msg:"获取页面url" } });
							 });
				      `);
			},
				//接收wenview h5的消息
			receiveMsg(option){
				console.log('接收到的消息参数'+JSON.stringify(option))
				
			},
			}
相关推荐
新中地GIS开发老师5 分钟前
WebGIS开发入门 | 从 Web 开发到地图开发,差别在哪儿?
前端·vue·webgis
IMPYLH13 分钟前
HTML 的 <p> 元素
前端·javascript·html
leoZ23114 分钟前
第 4 篇:布局骨架——页面壳、栅格、卡片
前端·javascript·vue.js·opencv·计算机视觉·数据挖掘·语音识别
何以解忧,唯有..23 分钟前
Vue 3 模板语法详解:从插值到指令的完整指南
前端·javascript·vue.js
invicinble41 分钟前
【无标题】
前端
EasyGBS44 分钟前
从接入到稳定播放:无插件直播H5视频流媒体播放器EasyPlayer.js如何撑起Web端流媒体
开发语言·前端·javascript
不可能片场1 小时前
nohup 之后进程还是死了:GUI 子进程的存活陷阱
前端·electron
名为沙丁鱼的猫7291 小时前
React/JSX 编码规范
前端·javascript·react.js
是吕先森1 小时前
【python】selenium实现web自动化测试
前端·python·selenium