移动端微信内置浏览器页面无法自动播放视频(React)

901 阅读1分钟

本文基于原文 ios 微信浏览器视频自动播放问题解决方法【亲测有效】

问题:

页面在微信内置浏览器中出现背景视频无法加载/自动播放

  <video loop autoPlay muted playsInline src="/ctx.mp4" />
  • 设备: ios/安卓 微信内置浏览器
  • 页面框架: Next.js

期待效果

  • 不显示控件(controls)
  • 不全屏播放
  • 自动循环播放

解决

如果使用的是typeScript,在顶部添加declare

declare global {
    interface Window {
        WeixinJSBridge?: any;
    }
}
declare const WeixinJSBridge: {
    invoke: (method: string, data: any, callback: (res: any) => void) => void;
};

为目标video标签添加id,已方便js定位这个元素

 <video id="bg-video" loop autoPlay muted playsInline src="/ctx.mp4" />

使用微信内置浏览器WeixinJSBridge触发视频播放

      function weChatPlayVideo() {
        if (window.WeixinJSBridge) {
            WeixinJSBridge.invoke('getNetworkType', {}, function () {
                const videoElement = document.getElementById('bg-video') as HTMLVideoElement;
                videoElement?.play();
            });
        }
    }

最后,添加useEffect,让页面加载后触发weChatPlayVideo()

    useEffect(() => {
        weChatPlayVideo()
    }, [])

完整代码

'use client'

import { useEffect, useState } from "react";

// Extend the Window interface to include WeixinJSBridge
// For WeChat build-in browser
declare global {
    interface Window {
        WeixinJSBridge?: any;
    }
}
declare const WeixinJSBridge: {
    invoke: (method: string, data: any, callback: (res: any) => void) => void;
};


export const CTX = () => {
    //Auto play video
    //ONLY for WeChat stupid built-in browser
    function weChatPlayVideo() {
        if (window.WeixinJSBridge) {
            WeixinJSBridge.invoke('getNetworkType', {}, function () {
                const videoElement = document.getElementById('bg-video') as HTMLVideoElement;
                videoElement?.play();
            });
        }
    }

    useEffect(() => {
        weChatPlayVideo()
    }, [])

    return (
        <div className="w-full h-screen">
            <video
                id="bg-video"
                loop
                autoPlay
                muted
                playsInline
                src="/ctx.mp4"
            />
        </div>
    );
};