Search code examples
c#asp.net-corewebview2

Microsoft WebView2: how to get the directory absolute path through 'showDirectoryPicker' in JavaScript


I want to access the absolute path of directory selected by user in WebView2, I know it is impossible in browser, but want to know if I can achieve this in WebView2


Solution

  • you could use showDirectoryPicker in JavaScript, but it won’t give the absolute path. i have prepared sample with the windows form which use the FolderBrowserDialog.

    index.html:

      <!DOCTYPE html>
    
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Directory Picker</title>
        <script>
            function selectDirectory() {
                // Send a message to .NET to open the folder picker
                window.chrome.webview.postMessage({
                    type: 'select-directory'
                });
            }
    
        </script>
    
    </head>
    <body>
        <h1>Select a Directory</h1>
        <button onclick="selectDirectory()">Choose Directory</button>
        <p id="result"></p>
    </body>
    
    </html>
    

    form1.cs:

    using Microsoft.Web.WebView2.Core;
    using System.Text.Json;
    
    namespace WebView2DirectoryPicker
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                InitializeAsync();
    
            }
            private async void InitializeAsync()
            {
                await webView21.EnsureCoreWebView2Async(null);
                webView21.CoreWebView2.WebMessageReceived += WebView_WebMessageReceived;
    
                // Use AppDomain.CurrentDomain.BaseDirectory for the path to work correctly from output directory
                string currentDir = AppDomain.CurrentDomain.BaseDirectory;
                webView21.Source = new Uri($"file:///{System.IO.Path.Combine(currentDir, "index.html")}");
            }
    
            private void WebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs args)
            {
                var message = args.WebMessageAsJson;
                var json = JsonDocument.Parse(message);
    
                if (json.RootElement.GetProperty("type").GetString() == "select-directory")
                {
                    // Open the Folder Browser Dialog to allow the user to select a folder
                    using (var folderDialog = new FolderBrowserDialog())
                    {
                        folderDialog.Description = "Select a directory";
                        folderDialog.UseDescriptionForTitle = true; // Only supported on Windows Vista and later
    
                        if (folderDialog.ShowDialog() == DialogResult.OK)
                        {
                            string selectedPath = folderDialog.SelectedPath;
    
                            // Display the selected path in a MessageBox for now
                            MessageBox.Show("Absolute Path: " + selectedPath);
    
                            // Optionally send the path back to JavaScript to display in the HTML page
                            webView21.CoreWebView2.ExecuteScriptAsync($"document.getElementById('result').innerText = 'Selected Path: {selectedPath}';");
                        }
                    }
                }
            }
    
        }
    }
    

    enter image description here