uni-app引入web-view组件后没有引用网页标题

发布于 1周前 作者 gougou168 来自 Uni-App

uni-app引入web-view组件后没有引用网页标题

开发环境 版本号 项目创建方式
Windows 10
HBuilderX 3.98

操作步骤:

  • uniappX中引入web-view并且真机运行没有,不能自动获取webview中的title

预期结果:

  • 可以根据网页变化动态显示title

实际结果:

  • 不显示title

bug描述:

  • uniappX中引入web-view并且真机运行没有,不能自动获取webview中的title

3 回复

uniapp可以动态改变标题,但是uniappx不可以


请收下,不用谢
uni-app-x webview组件不支持获取网页内容解决方案

uni-app 中使用 web-view 组件时,默认情况下不会自动显示网页的标题。web-view 组件只是嵌入了一个网页,但并不会自动处理网页的标题显示。如果你希望在 uni-app 中显示嵌入网页的标题,可以通过以下几种方式来实现:

方法一:手动设置页面标题

你可以在 web-view 加载完成后,通过 uni.setNavigationBarTitle 方法来手动设置页面标题。具体步骤如下:

  1. web-view 组件上绑定 @load 事件,监听网页加载完成。
  2. @load 事件中,通过 uni.setNavigationBarTitle 设置标题。
<template>
  <view>
    <web-view :src="url" @load="onWebViewLoad"></web-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      url: 'https://example.com' // 替换为你要加载的网页地址
    };
  },
  methods: {
    onWebViewLoad(event) {
      // 这里可以根据需要设置标题
      uni.setNavigationBarTitle({
        title: '自定义标题' // 替换为你想要的标题
      });
    }
  }
};
</script>

方法二:通过网页的 title 动态设置标题

如果你希望动态获取网页的 title 并设置为 uni-app 的标题,可以通过 web-view@message 事件与网页进行通信,获取网页的 title

  1. 在网页中通过 JavaScript 获取 document.title,并通过 postMessage 发送给 uni-app
  2. uni-app 中监听 @message 事件,获取网页的 title 并设置。

网页中的代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>网页标题</title>
  <script>
    // 网页加载完成后,发送标题给 uni-app
    window.onload = function() {
      const title = document.title;
      window.parent.postMessage({ title: title }, '*');
    };
  </script>
</head>
<body>
  <h1>Hello, World!</h1>
</body>
</html>

uni-app 中的代码:

<template>
  <view>
    <web-view :src="url" @message="onWebViewMessage"></web-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      url: 'https://example.com' // 替换为你要加载的网页地址
    };
  },
  methods: {
    onWebViewMessage(event) {
      const title = event.detail.data[0].title;
      uni.setNavigationBarTitle({
        title: title
      });
    }
  }
};
</script>

方法三:使用 uni-apponNavigationBarChange 事件

如果你希望监听导航栏的变化,可以使用 uni-apponNavigationBarChange 事件来动态设置标题。

<template>
  <view>
    <web-view :src="url"></web-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      url: 'https://example.com' // 替换为你要加载的网页地址
    };
  },
  onNavigationBarChange(e) {
    // 这里可以根据需要设置标题
    uni.setNavigationBarTitle({
      title: '自定义标题' // 替换为你想要的标题
    });
  }
};
</script>
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!