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

能否在Flutter WebView中运行TypeScript?视频播放问题技术咨询

Flutter WebView里运行TypeScript及触发视频播放的方法

能不能直接在Flutter WebView里跑TypeScript?

不行。WebView的JS引擎只能执行原生JavaScript,TypeScript是JS的超集,必须先编译成JS才能在WebView里运行。

对应你现有JS代码的TypeScript实现

步骤1:编写TS逻辑

先写出带类型校验的TS代码,逻辑和原JS一致,但更严谨:

const playVideo = (): void => {
  const videoElement = document.getElementById('spot-video') as HTMLVideoElement;
  if (videoElement) {
    videoElement.play().catch(err => {
      console.error('视频播放失败:', err);
    });
  } else {
    console.error('没找到ID为spot-video的视频元素');
  }
};

playVideo();

步骤2:把TS编译成JS

用TypeScript编译器tsc把上面的代码转成JS,得到的代码大概是这样:

var playVideo = function () {
    var videoElement = document.getElementById('spot-video');
    if (videoElement) {
        videoElement.play().catch(function (err) {
            console.error('视频播放失败:', err);
        });
    } else {
        console.error('没找到ID为spot-video的视频元素');
    }
};
playVideo();

步骤3:在Flutter WebView里执行编译后的JS

把编译好的JS代码放到runJavascriptReturningResult里就行,和你原来的写法差不多:

WebView(
    initialUrl: privacyUrl,
    javascriptMode: JavascriptMode.unrestricted,
    gestureNavigationEnabled: false,
    debuggingEnabled: true,
    onWebViewCreated: (controller) {
      webController = controller;
    },
    onPageFinished: (url) {
      webController.runJavascriptReturningResult('''
        (function() {
          var videoElement = document.getElementById('spot-video');
          if (videoElement) {
            videoElement.play().catch(function(err) {
              console.error('视频播放失败:', err);
            });
          } else {
            console.error('没找到ID为spot-video的视频元素');
          }
        })()
      ''');
    },
  ),

额外情况:如果网页是你自己用TS开发的

要是你加载的网页是自己用TS写的,可以直接在网页的TS代码里提前写好播放逻辑,然后暴露成全局方法,再从Flutter里调用:

  • 网页TS代码:
(window as any).playSpotVideo = (): void => {
  const videoElement = document.getElementById('spot-video') as HTMLVideoElement;
  videoElement?.play().catch(console.error);
};
  • Flutter里调用:
webController.runJavascriptReturningResult('playSpotVideo();');

内容的提问来源于stack exchange,提问作者K K Muhammed Fazil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:10:33