TWebView2

Source: source/classes/twebview2.prg

Overview

TWebView2 embeds Microsoft Edge WebView2 in a FiveWin window or dialog. Use it to host modern HTML/CSS/JS UIs next to native FWH controls. Requires the WebView2 Runtime (Evergreen or Fixed Version).

Desktop + Web with one UI

Sample samples/DesktopWeb/login.prg shows a full pattern where desktop and browser share the same HTML/CSS/JS:

// Desktop shell (simplified)
StartHttpServer( 8080 )
oWeb := TWebView2():New()
oWeb:Navigate( "http://localhost:8080/" )
oWeb:Run()

Build with multi-thread VM: samples\DesktopWeb\build.bat or build_new.bat login hm64 -mt. Demo users: admin/1234, demo/demo.

FWH 26.09

The extended API, including bOnConsole and EnableConsole, is available from FWH 26.09, day 12 (12 September 2026). These are FWH library features, not features supplied by merely updating the Microsoft Runtime. Older libraries may lack the DATA setter _BONCONSOLE and the EnableConsole method.

Method reference

C = character string, N = number, L = logical, HWND = Windows handle. NIL means no status is returned; it is not a success flag. "delegated" means the underlying window method supplies the return; "virtual" is an empty hook. Async dispatch and final success are separate.

SignatureReturnBehavior
New( oWndParent, cUserDataFolder, cBrowserExecutableFolder )SelfCreates the view in oWndParent, or creates its own window when NIL. Check hWebView for creation failure. Empty profile path uses %LOCALAPPDATA%\FWH_webview2_UserData. The third argument selects a Fixed Version Runtime folder at creation time.
Navigate( cUrl )NILStarts navigation; completion is reported by bOnNavigationCompleted.
NavigateEx( cUrl, cMethod, cHeaders, cBody )LDispatches an HTTP request. Empty method defaults to GET; headers use Name: Value lines separated by CRLF. .T. means dispatched, not an HTTP success. On older runtimes only plain GET can fall back to Navigate.
SetHtml( cHtml )NILLoads an HTML string.
Eval( cJavaScript )NILExecutes JavaScript in the page; its JSON-encoded result arrives asynchronously in bOnEval.
InjectJavascript( cScript )NILAppends a script element through Eval. Page CSP can block it; template-literal escapes also apply. Use Eval for direct execution.
GoBack()NILNavigates back in history.
GoForward()NILNavigates forward in history.
Reload()NILReloads the current page.
Stop()NILStops the current navigation.
Print()NILCalls window.print() through Eval; it is not a synchronous print-success result.
CanGoBack()LWhether a previous history entry is available; .F. if unavailable.
CanGoForward()LWhether a following history entry is available; .F. if unavailable.
GetSource()CReturns the current URL, not the page HTML; empty string if unavailable.
GetDocumentTitle()CReturns the document title, or an empty string.
GetBrowserVersion()CReads the installed Evergreen Runtime version from the Windows registry, or an empty string. It does not query the selected Fixed Version folder.
SetZoomFactor( nZoom )NILSets browser zoom only for 0.1 < nZoom < 10.0.
GetZoomFactor()NReturns browser zoom; defaults to 1.0 without a controller.
SetSizeRatio( nRatio )NStores and returns nRatio (initially 1.0); it does not resize the browser or change zoom.
GetSizeRatio()NReturns the stored application scale ratio.
SetSize( nWidth, nHeight )NILSets the WebView bounds in pixels.
SetTitle( cText )LCalls SetWindowText on oWnd; returns the Windows API success flag.
Center()delegatedDelegates to oWnd:Center(); its return belongs to the window class.
Run()delegatedDelegates to oWnd:Activate(); not a WebView status result.
SetParent( oWnd )HWNDStores the new parent, sets child/visible styles and reparents the window. Returns SetParent old-parent handle; zero can also mean no previous parent.
GetWindow()HWNDReturns oWnd:hWnd, the associated FWH window handle.
SetUserAgent( cUserAgent )NILChanges the browser user agent.
SetBackGroundColor( nRgb )NILSets the controller background using a Windows RGB value.
OpenDevToolsWindow( lOnOff )NILOpens developer tools when .T.; .F. does not close an already opened tools window.
ShowDownloads( lOnOff )NILControls whether the default UI is shown for future download-start events; .F. marks them handled. It does not open or close an existing download dialog.
SetDefaultScriptDialogs( lOn )NILEnables/disables default JS dialogs; NIL defaults to .T. Use bOnScriptDialog for acceptance.
SetDefaultContextMenus( lOn )NILEnables/disables default right-click menus; NIL defaults to .T.
CloseWebView()NILTears down the browser/controller; the class object remains.
Reinitialize()NILTears down and recreates the environment/controller, then reattaches events. No success flag is returned; restore page/application state yourself.
Reregister()NILReattaches zoom, script-dialog and web-resource handlers; removes old registrations first.
End()NILDestroys the native view, clears hWebView and removes the object from the view registry.
SetContextMenuExclude( cCsv )CStores and returns the CSV list (NIL becomes empty). Per-item menu filtering is not implemented with the bundled SDK.
EnableConsole( lOnOff )LSets and returns lConsole (NIL defaults to .T.). See the console section for injection and disable semantics.
CapturePreview( cPngPath )LStarts asynchronous PNG capture. .F. means not dispatched; .T. means wait for bOnCapturePreview(lOk,cPath,hWebView).
PrintToPdf( cPdfPath, lLandscape )LStarts asynchronous PDF export (.F./NIL landscape flag means portrait). Requires supported runtime interfaces. Final result is bOnPrintToPdf(lOk,cPath,hWebView), not this dispatch flag.
AddWebResourceRequestedFilter( cUri, nContext )NILAdds a URL-pattern filter; NIL context defaults to WV_CONTEXT_ALL (0). bOnWebResource receives matches.
RemoveWebResourceRequestedFilter( cUri, nContext )NILRemoves a URL-pattern filter; NIL context defaults to WV_CONTEXT_ALL (0). bOnWebResource receives matches.
AddHostObject( cName ).F.Not implemented: no IDispatch host object is registered.
RemoveHostObject( cName ).T.Compatibility no-op; it removes no native host object.
ClearBrowsingData( nKinds ).T.Queues JS deletion of accessible cookies, local/session storage and Cache Storage; NIL kinds becomes 0. nKinds is reported in the acknowledgment but does not select native data categories. The asynchronous callback reports script acknowledgment, not proof that every item was removed.
ClearSession().T.Alias for ClearBrowsingData(0); not a full-profile wipe.
ClearAllBrowsingData().T.Alias for ClearBrowsingData(0); despite its name it does not remove HttpOnly cookies or the full profile.
Diag( nKind )NNIL defaults to 0. 0/1/2: registration HRESULT for zoom/dialog/web-resource. 3/4/5: event hit counters. Other values use the web-resource hit counter; absent native view returns -999.
Terminate()virtualEmpty virtual hook; it does not replace End().
Destroy()virtualEmpty virtual hook; it does not replace End().

Event blocks

Assign blocks with the arguments below. hWebView is the native view pointer, not the FWH object; bOnBind instead receives oWebView as its second argument. Return values only affect behavior where stated.

SignatureBehavior
bOnBind( uParams, oWebView )Receives ordinary SendToFWH arguments; return ignored. One-element arrays are unwrapped; internal console/cleanup envelopes have separate callbacks.
bOnEval( cJson, hWebView )JSON-encoded JavaScript result; return ignored.
bOnConsole( cJson, hWebView )Console JSON described below; return ignored.
bOnNavigationCompleted( cUrl, hWebView )Top-level navigation completed. Return ignored.
bOnSourceChanged( cUrl, hWebView )Source URL changed. Return ignored.
bOnDocumentTitleChanged( cTitle, hWebView )Document title changed. Return ignored.
bOnHistoryChanged( lCanBack, lCanFwd, hWebView )History availability changed. Return ignored.
bOnFrameNavCompleted( cUrl, hWebView )Frame navigation completed. Return ignored.
bOnCapturePreview( lOk, cPath, hWebView )Final PNG capture/file-write result. Return ignored.
bOnPrintToPdf( lOk, cPath, hWebView )Final PDF export result. Return ignored.
bOnClearBrowsingData( lOk, cWhat, hWebView )JS acknowledgment: .T., "javascript"; not verified full-profile erasure. Return ignored.
bOnZoomFactorChanged( nZoom, hWebView )Browser zoom changed. Return ignored.
bOnProcessFailed( nKind, hWebView )Browser process failure; WV_FAIL_* kind. Return ignored.
bOnFullScreen( lFull, hWebView )HTML full-screen state changed. Return ignored.
bOnNavigationStarting( cUrl, hWebView )Return .T. to cancel; other/non-logical values do not cancel.
bOnFrameNavStarting( cUrl, hWebView )Return .T. to cancel; other/non-logical values do not cancel.
bOnNewWindow( cUrl, hWebView )Notification only: the native view navigates to this URL and marks the request handled; callback return does not choose another window.
bOnPermission( cUrl, nKind, hWebView )Return WV_PERM_ALLOW (1), WV_PERM_DENY (2), or 0 for default; nKind is the runtime permission kind.
bOnWebResource( cUrl, nContext, hWebView )Return .T. or a nonzero number to block with empty HTTP 403; otherwise allow. Install filters first.
bOnScriptDialog( cUri, nKind, cMsg, cDefault, hWebView )Return .T. to Accept; .F. leaves default handling (or no dialog if defaults disabled). An installed block returning a non-logical value is treated as .T. WV_DIALOG_* kinds. Prompt-result replacement is not exposed.
bOnHostObject( cObjName, cMethod, cArg, hWebView )Reserved hook returning C; no native host-object registration is implemented.

JavaScript console

EnableConsole(.T.) wraps console.log/warn/error/info without removing the original console output and adds a JavaScript error listener. It sends an internal envelope through SendToFWH; bOnConsole receives the inner JSON string, not the outer envelope. args contains strings: objects are JSON-stringified. line is present for window error events, and is absent for ordinary console calls.

Call EnableConsole(.T.) after each top-level navigation: the wrapper is installed once per document. EnableConsole(.F.) stops delivery through the console dispatcher, but does not undo the already installed JavaScript wrapper. Its logical return is the stored flag, not proof of successful injection. Console traffic is separate from ordinary bOnBind messages.

Example payloads

{
  "type": "log",
  "args": [
    "ready",
    "{\"count\":2}"
  ],
  "url": "https://example.com/"
}

{
  "type": "error",
  "args": [
    "Uncaught ReferenceError: x is not defined"
  ],
  "url": "https://example.com/",
  "line": 12
}

Console example

oWeb := TWebView2():New( oWnd )
IF ! Empty( oWeb:hWebView )
   oWeb:bOnConsole := { | cJson, hWebView | LogConsole( cJson ) }
   oWeb:bOnNavigationCompleted := { | cUrl, hWebView | oWeb:EnableConsole( .T. ) }
   oWeb:Navigate( "https://example.com/" )
ENDIF

STATIC FUNCTION LogConsole( cJson )
   LOCAL hData
   hb_jsonDecode( cJson, @hData )
   IF ValType( hData ) == "H"
      // hData[ "type" ], hData[ "args" ], hData[ "url" ]
      // hData[ "line" ]: only for a window error
      OutputDebugString( cJson )
   ENDIF
RETURN NIL

Library compatibility

For an application that supports earlier FWH libraries, guard both the DATA assignment and EnableConsole call. Use the same check when enabling tracing after navigation. This only skips console diagnostics; ordinary SendToFWH/bOnBind traffic is unchanged.

IF __objHasMsg( oWeb, "_BONCONSOLE" ) .AND. ;
   __objHasMsg( oWeb, "ENABLECONSOLE" )
   oWeb:bOnConsole := { | cJson, hWebView | LogConsole( cJson ) }
   oWeb:EnableConsole( .T. )
ENDIF

Limits and runtime requirements

AddHostObject is not implemented. SetContextMenuExclude stores the list but does not filter menu items. Browsing-data cleanup is JavaScript-level, not a full-profile wipe, and cannot clear HttpOnly cookies. Async PNG/PDF results must be checked through their events. Runtime interface availability can limit PDF, downloads and HTTP requests. See the example samples/webview2/wvdemo.prg + pulse.html and constants WV_CONTEXT_*, WV_DIALOG_*, WV_PERM_* and WV_FAIL_* in include/WebView2.ch.

For Remote View + WebView2, see samples/RemoteView/testrvweb.prg and Remote View.

See Classes Alphabetical for full class list.

See Also