TsgcWebView2 | Download Control

TsgcWebView2 provides events to intercept, monitor, and control file downloads initiated by the browser.

Download Events

The OnDownloadStarting event fires when a download begins. You can cancel the download, change the destination file path, or let it proceed with the default behavior.


procedure TFormMain.sgcWebView21DownloadStarting(Sender: TObject;
  const aURI, aResultFilePath: string;
  var aCancel, aHandled: Boolean; var aFilePath: string);
begin
  // Log the download
  Memo1.Lines.Add('Download starting: ' + aURI);
  Memo1.Lines.Add('Default path: ' + aResultFilePath);

  // Cancel downloads of .exe files
  if Pos('.exe', LowerCase(aURI)) > 0 then
  begin
    aCancel := True;
    ShowMessage('Executable downloads are blocked.');
  end;
end;

Download Progress

The OnDownloadProgress event fires periodically during the download, reporting bytes received and total bytes expected.


procedure TFormMain.sgcWebView21DownloadProgress(Sender: TObject;
  aBytesReceived, aTotalBytes: Int64);
begin
  if aTotalBytes > 0 then
    ProgressBar1.Position :=
      Round((aBytesReceived / aTotalBytes) * 100)
  else
    ProgressBar1.Position := 0;

  LabelStatus.Caption := Format('Downloaded %d of %d bytes',
    [aBytesReceived, aTotalBytes]);
end;

Download Complete

The OnDownloadCompleted event fires when the download finishes. Check aState to determine whether the download succeeded, was cancelled, or failed.


procedure TFormMain.sgcWebView21DownloadCompleted(Sender: TObject;
  const aFilePath: string; aState: Integer);
begin
  case aState of
    0: // Completed
      ShowMessage('Download complete: ' + aFilePath);
    1: // Cancelled
      ShowMessage('Download was cancelled.');
    2: // Failed
      ShowMessage('Download failed.');
  end;
end;

Custom Download Path

Set the aFilePath parameter in OnDownloadStarting to redirect the download to a custom location. Set aHandled to True to suppress the default save dialog.


procedure TFormMain.sgcWebView21DownloadStarting(Sender: TObject;
  const aURI, aResultFilePath: string;
  var aCancel, aHandled: Boolean; var aFilePath: string);
begin
  // Redirect all downloads to a custom folder
  aFilePath := 'C:\Downloads\' + ExtractFileName(aResultFilePath);
  aHandled := True; // suppress the default save dialog
end;