- 1 year ago
UWP Webview Contenteditable div
Comment
1 / 1
To enable editing of a div
element inside a WebView
in a UWP (Universal Windows Platform) app, you need to use the InvokeScriptAsync
method of the WebView
control to run JavaScript code that sets the contenteditable
attribute of the div
to true
. Here's how you can do it:
- Add a
WebView
control to your XAML layout:
xml<Grid>
<WebView x:Name="webView" />
</Grid>
- In the code-behind of your XAML page, load the HTML content into the
WebView
and then enable thecontenteditable
attribute using JavaScript:
csharpusing System;
using Windows.UI.Xaml.Controls;
namespace YourAppName
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
webView.NavigationCompleted += WebView_NavigationCompleted;
LoadWebViewContent();
}
private async void LoadWebViewContent()
{
// Load the HTML content into the WebView
string htmlContent = "<html><body><div id=\"editableDiv\">Type your text here</div></body></html>";
webView.NavigateToString(htmlContent);
}
private async void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
// Enable editing of the div element using JavaScript
string script = "document.getElementById('editableDiv').contentEditable = true;";
await webView.InvokeScriptAsync("eval", new string[] { script });
}
}
}
In this example, we use the NavigationCompleted
event to wait until the WebView
has finished loading the HTML content. Then, we use the InvokeScriptAsync
method to run the JavaScript code that sets the contenteditable
attribute of the div
with the ID "editableDiv" to true
.
Now, the div
element inside the WebView
will be editable, and the user can type text directly into it.