Search code examples
xmlxsltmfcwebview2

How can you perform a XML / XSL transformation for local files with the WebView2 control?


Microsoft Edge (and thus the WebView2 control) allows us to navigate to XML files which get transformed into HTML files. But this does not work when the XML file is local to the PC.

I appreciate that we we could potentially create a local web server and use localhost but that is a lot of work. The CHtmlView control did not have this issue.


I noticed a similar question How to use WebView2 to display XML content using XSL transforms? but it was related to WPF. No doubt the same options could be used with the WebView2 object.


Solution

  • I had a discussion on the WebView2 GitHub website and a solution was found.

    You need to make use of a command line option --allow-file-access-from-files which will then allow local XML links to be used. When invoking the Microsoft Edge you just pass it on the command line. But this is how you do it with the WebView2 control:

    void CWebBrowser::InitializeWebView()
    {
       CloseWebView();
    
       CString subFolder = GetInstallPath();
       CString appData = GetUserDataFolder();
    
       auto options = Microsoft::WRL::Make<CoreWebView2EnvironmentOptions>();
       CHECK_FAILURE(options->put_AdditionalBrowserArguments(L"--allow-file-access-from-files"));
    
       HRESULT hr = CreateCoreWebView2EnvironmentWithOptions(
           subFolder,
           appData,
           options.Get(),
           Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
               this,
               &CWebBrowser::OnCreateEnvironmentCompleted).Get());
    
       if (!SUCCEEDED(hr))
       {
          CString text;
          if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
          {
             text = L"Cannot found the WebView2 component.";
          }
          else
          {
             text = L"Cannot create the webview environment.";
          }
    
          ShowFailure(hr, text);
       }
    }
    

    The above snippet shows how to use the CoreWebView2EnvironmentOptions parameter.