uniapp如何获取webview的url

我在uniapp中使用了webview组件加载网页,但需要获取当前webview的url地址。请问应该如何实现?有没有具体的代码示例或方法可以分享?

2 回复

在uniapp中,可以通过@load事件监听webview加载完成,然后使用e.detail.url获取当前页面的URL。示例代码:

<web-view src="https://example.com" @load="onWebviewLoad"></web-view>

methods: {
  onWebviewLoad(e) {
    console.log(e.detail.url)
  }
}

在 UniApp 中,可以通过 webview 组件的 @load 事件或 @message 事件来获取其加载的 URL。以下是具体方法:

方法一:使用 @load 事件

webview 组件上绑定 @load 事件,当页面加载完成时触发,通过事件对象获取 URL。

<template>
  <webview src="https://example.com" @load="onWebviewLoad"></webview>
</template>

<script>
export default {
  methods: {
    onWebviewLoad(event) {
      const url = event.detail.url; // 获取 webview 当前加载的 URL
      console.log('WebView URL:', url);
    }
  }
}
</script>

方法二:使用 @message 事件(需与网页配合)

如果网页支持,可以通过 postMessage 从网页向 UniApp 传递 URL。

  1. 在 UniApp 中
<template>
  <webview src="https://example.com" @message="onWebviewMessage"></webview>
</template>

<script>
export default {
  methods: {
    onWebviewMessage(event) {
      const data = event.detail.data; // 接收网页发送的数据
      if (data.url) {
        console.log('WebView URL:', data.url);
      }
    }
  }
}
</script>
  1. 在网页中(需嵌入以下代码):
// 网页加载完成后发送 URL 到 UniApp
window.addEventListener('load', function() {
  if (window.parent && window.parent.postMessage) {
    window.parent.postMessage({ url: window.location.href }, '*');
  }
});

注意事项:

  • 跨域限制:如果 webview 加载的网页与 UniApp 不同源,可能无法通过 @load 事件获取完整 URL(受浏览器安全策略限制)。
  • 平台差异:在部分平台(如 App 端)可能支持更完整的 URL 获取,但 H5 端受限于浏览器环境。
  • 推荐使用方法一,简单直接。若需动态或实时获取,确保网页合作或使用 UniApp 的 webview 组件 API。

以上方法适用于 UniApp 的 Vue 页面结构,根据实际需求选择即可。

回到顶部