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

Ionic5使用@angular/youtube-player库iOS端无法显示问题修复求助

可按以下步骤修复iOS端不显示的问题:

  • 第一步:修复高度适配问题
    iOS WebView 无法识别 youtube-player 组件的 height="auto" 属性,必须手动固定容器的宽高比,修改代码如下:
// component.html
<div class="youtube-container">
  <youtube-player 
    *ngIf="isYtApiReady"
    [videoId]="attributes?.youTubeLink" 
    width="100%" 
    height="100%"
  ></youtube-player>
</div>
// component.scss
.youtube-container {
  position: relative;
  width: 100%;
  padding-bottom: 56.25%; /* 适配16:9的视频比例,其他比例可自行调整数值 */
  height: 0;
}
.youtube-container youtube-player {
  position: absolute;
  top: 0;
  left: 0;
  width: 100% !important;
  height: 100% !important;
}
  • 第二步:调整API加载时序
    iOS对资源加载的时序要求更严格,需要等YouTube iframe API完全初始化完成后再渲染播放器,修改组件逻辑:
// component.ts
export class YouTubeComponent implements OnInit {
  // 控制播放器渲染时机的标记位
  isYtApiReady = false;

  ngOnInit(): void {
    // 若API已加载直接标记就绪
    if (window.YT) {
      this.isYtApiReady = true;
      return;
    }
    // 监听API加载完成的全局回调
    window['onYouTubeIframeAPIReady'] = () => {
      this.isYtApiReady = true;
    };
    loadScript('https://www.youtube.com/iframe_api');
  }
}
  • 第三步:配置iOS端WebView权限
    如果使用Capacitor打包,在capacitor.config.ts中添加WebView播放权限配置:
// capacitor.config.ts
const config = {
  // 其余原有配置保持不变
  ios: {
    webView: {
      allowsInlineMediaPlayback: true,
      mediaPlaybackRequiresUserAction: false
    }
  }
};
export default config;

如果使用Cordova打包,在项目根目录的config.xml的iOS配置段添加如下配置:

<preference name="AllowInlineMediaPlayback" value="true" />
<preference name="MediaPlaybackRequiresUserAction" value="false" />

完成以上修改后重新打包iOS应用即可正常显示播放器。

内容的提问来源于stack exchange,提问作者Raphaël Balet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 09:15:07