You need to enable JavaScript to run this app. 如何将TEdgeBrowser的console.log输出重定向到Delphi应用
优惠活动
大模型
产品
解决方案
定价
更多

如何将TEdgeBrowser的console.log输出重定向到Delphi应用

Delphi中TEdgeBrowser控制台输出重定向方案

核心实现原理

TEdgeBrowser底层基于Edge Chromium内核,要捕获控制台输出,只需通过内核提供的ICoreWebView2DevToolsProtocolEventReceiver接口监听DevTools的Runtime.consoleAPICalled事件即可。

具体实现步骤

  • 第一步:确保TEdgeBrowser完成初始化,等待OnCreateWebViewCompleted事件触发后再进行事件绑定操作,避免内核未就绪导致绑定失败。
  • 第二步:获取DevTools协议接收器,注册Runtime.consoleAPICalled事件监听:
uses
  Winapi.WebView2, Winapi.ActiveX, System.SysUtils;

procedure TForm1.EdgeBrowser1CreateWebViewCompleted(Sender: TCustomEdgeBrowser; AResult: HResult);
var
  LDevToolsProtocolEventReceiver: ICoreWebView2DevToolsProtocolEventReceiver;
begin
  if Succeeded(AResult) then
  begin
    // 启用Runtime域
    EdgeBrowser1.ExecuteDevToolsMethod(0, 'Runtime.enable', '{}', nil);
    
    // 获取consoleAPICalled事件的接收器
    EdgeBrowser1.DefaultInterface.GetDevToolsProtocolEventReceiver(
      'Runtime.consoleAPICalled',
      LDevToolsProtocolEventReceiver
    );
    
    // 绑定事件回调
    if Assigned(LDevToolsProtocolEventReceiver) then
    begin
      LDevToolsProtocolEventReceiver.add_DevToolsProtocolEventReceived(
        DevToolsConsoleEventReceived,
        nil
      );
    end;
  end;
end;
  • 第三步:实现事件回调函数,解析DevTools返回的JSON数据,提取控制台输出内容:
uses
  System.JSON;

procedure TForm1.DevToolsConsoleEventReceived(
  sender: ICoreWebView2;
  args: ICoreWebView2DevToolsProtocolEventReceivedEventArgs
): HResult;
var
  LParamJson: PWideChar;
  LJsonValue: TJSONValue;
  LLogType, LLogContent: string;
  LArgsArray: TJSONArray;
begin
  Result := S_OK;
  if not Assigned(args) then Exit;

  // 获取事件参数的JSON字符串
  args.get_ParameterObjectAsJson(LParamJson);
  try
    LJsonValue := TJSONObject.ParseJSONValue(LParamJson);
    if Assigned(LJsonValue) then
    try
      // 提取日志类型:log/info/warn/error等
      LLogType := LJsonValue.GetValue<string>('type');
      // 提取日志参数数组
      LArgsArray := LJsonValue.GetValue<TJSONArray>('args');
      if Assigned(LArgsArray) and (LArgsArray.Count > 0) then
      begin
        // 取第一个参数的内容作为日志文本,多参数可自行遍历
        LLogContent := LArgsArray.Items[0].GetValue<string>('value');
        // 示例:将日志输出到Memo组件
        Memo1.Lines.Add(Format('[%s] %s', [LLogType, LLogContent]));
      end;
    finally
      LJsonValue.Free;
    end;
  finally
    CoTaskMemFree(LParamJson);
  end;
end;

注意事项

  • 代码中用到的JSON解析类来自System.JSON单元,需要自行在uses中引入。
  • 如果需要捕获console.error的堆栈信息,可以从返回的JSON的stackTrace字段中提取对应信息。
  • 高版本Delphi(10.4.1及以上)自带的TEdgeBrowser已经封装了相关接口,低版本需要自行引入最新的WebView2头文件。
  • 不需要手动打开DevTools面板,事件监听在后台即可正常运行,不影响用户正常使用浏览器功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 14:45:01