You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS端webview嵌入竖屏Youtube直播时iframe内部视频高度异常

iOS端Youtube iframe嵌入竖屏直播尺寸异常修复方案

测试范围

  • 测试设备:iPhone 11(iOS 15)、iPhone 6s(iOS 14)、iPhone 8(iOS 14)
  • 测试环境:App内置webview、Safari、Chrome

问题说明

参考Youtube iframe官方API文档开发,在iOS应用的webview中嵌入Youtube iframe使用。通过Youtube移动端APP「go live」功能开启竖屏模式直播时,iOS端iframe本身高度正常(右下角可见Youtube logo),但iframe内部的直播视频高度极小,仅等同于横屏视频尺寸。
初始iframe样式参数:宽度为100vw,高度为177vw,页面内仅存在该iframe无其他元素。
异常效果截图:
iOS端Youtube竖屏视频问题截图

初始实现代码

const DebugVertical = (props) => {
    const { videoId } = props.match.params;
    return (
        <iframe
        id={`youtube-embed-${videoId}`}
        src={`https://www.youtube.com/embed/${videoId}?enablejsapi=1&controls=0&playsinline=1&rel=0&fs=0`}
        frameBorder="0"
        allow="accelerometer; autoplay; encrypted-media; gyroscope"
        style={{ width: "100vw", height: "177vw" }}
        />
    );
};

修复方案

1. 调整webview基础配置

iOS端原生webview需要将allowsInlineMediaPlayback属性设置为true,禁止系统强制拉起视频全屏播放,避免触发尺寸适配异常。

2. 调整嵌入实现代码

新增外层比例容器,同时补充iframe缺失的适配参数,接入JS API强制适配尺寸,修改后代码如下:

import { useEffect } from 'react';

const DebugVertical = (props) => {
    const { videoId } = props.match.params;
    const playerId = `youtube-embed-${videoId}`;

    useEffect(() => {
        // 监听Youtube播放器就绪事件
        const onPlayerReady = (event) => {
            // 强制指定播放质量,触发播放器按容器尺寸适配
            event.target.setPlaybackQuality('hd1080');
            event.target.playVideo();
        };

        // 初始化Youtube播放器实例
        window.YT && new window.YT.Player(playerId, {
            events: {
                'onReady': onPlayerReady
            }
        });
    }, [videoId, playerId]);

    return (
        <div style={{ width: '100vw', aspectRatio: '9/16', overflow: 'hidden' }}>
            <iframe
                id={playerId}
                src={`https://www.youtube.com/embed/${videoId}?enablejsapi=1&controls=0&playsinline=1&rel=0&fs=0&iv_load_policy=3&modestbranding=1&origin=${window.location.origin}`}
                frameBorder="0"
                allow="accelerometer; autoplay; encrypted-media; gyroscope"
                style={{ width: "100%", height: "100%" }}
            />
        </div>
    );
};

3. 兼容说明

如果页面没有提前引入Youtube JS SDK,需要在组件挂载时动态加载对应官方SDK脚本。
如果需要兼容iOS 14及更低版本,可将外层容器的aspectRatio样式替换为传统padding-top实现:

.container {
    width: 100vw;
    height: 0;
    padding-top: 177.78%;
    position: relative;
}
.container iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

内容的提问来源于stack exchange,提问作者Sushil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:27:04