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))
				
			},
			}
相关推荐
江号软件分享25 分钟前
有效保障隐私,如何安全地擦除电脑上的敏感数据
前端
web守墓人1 小时前
【前端】ikun-markdown: 纯js实现markdown到富文本html的转换库
前端·javascript·html
为风而战1 小时前
uni-app X APP在线升级 解决【uni-upgrade-center-app】未配置uni-upgrade-center 问题
uni-app
Savior`L2 小时前
CSS知识复习5
前端·css
许白掰2 小时前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器
雪碧聊技术6 小时前
uniapp如何创建并使用组件?组件通过Props如何进行数据传递?
uni-app·创建组件·使用组件·props数据传递
中微子6 小时前
🔥 React Context 面试必考!从源码到实战的完整攻略 | 99%的人都不知道的性能陷阱
前端·react.js
@Dream_Chaser6 小时前
uniapp页面间通信
uni-app
中微子7 小时前
React 状态管理 源码深度解析
前端·react.js
加减法原则8 小时前
Vue3 组合式函数:让你的代码复用如丝般顺滑
前端·vue.js