Hi @BRENT MALNACK , Welcome to Microsoft Q&A,
Before attempting to send a message via window.chrome.webview.postMessage, make sure that the WebView2 control is fully initialized and loaded with the correct content.
Resizing the form causes the message to fire, which may be related to the layout and rendering mechanism of WebView2. You can try to force a redraw to be triggered after the SVG content is loaded, without needing to resize the form.
Make sure you're using the latest version of the WebView2 SDK and runtime. There may be some issues with older versions.
If the SVG doesn't render when you reload the form, it may be because of timing of the content loading. Make sure to render the SVG after the HTML content is loaded.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitializeWebView();
}
private async void InitializeWebView()
{
await webView.EnsureCoreWebView2Async(null);
webView.CoreWebView2.NavigationCompleted += WebView_NavigationCompleted;
webView.CoreWebView2.WebMessageReceived += WebView_WebMessageReceived;
LoadSvgContent();
}
private void WebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
string script = @"
function boxClicked(folderId) {
window.chrome.webview.postMessage(folderId);
}
";
webView.CoreWebView2.ExecuteScriptAsync(script);
}
private void WebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
string message = e.TryGetWebMessageAsString();
MessageBox.Show($"Received message: {message}");
}
private void LoadSvgContent()
{
StringBuilder svgBuilder = new StringBuilder();
svgBuilder.AppendLine("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 500 500\" preserveAspectRatio=\"xMidYMid meet\" id=\"svg-content\">");
svgBuilder.AppendLine("<script>function boxClicked(folderId) { window.chrome.webview.postMessage(folderId); }</script>");
svgBuilder.AppendLine("<rect x=\"0\" y=\"0\" width=\"100\" height=\"100\" fill=\"lightgray\" stroke=\"black\" stroke-width=\"2\" onclick=\"boxClicked('folder1')\"/>");
svgBuilder.AppendLine("</svg>");
webView.NavigateToString(svgBuilder.ToString());
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.