Visual Studio Code Webview Example



Xamarin forums are UI's & shared code (C#) are same. To develop multi-platforms Applications, run all the projects (Android, Windows, IOS) on Same Time. Visual Studio 2017 Enterprise; The steps given below are required to be followed in order to create simple Android Web View Application, using Xamarin.Forms in Visual Studio 2017. To obtain information about Microsoft Visual Studio and the tools for developing Windows apps, go to Visual Studio. Related topics Samples. FullScreenMode ShareSource RSS reader sample. WebView control IUriToStreamResolver interface. System requirements. Client: Windows 10. Server: Windows Server 2016 Technical Preview. WebView Example In Android Studio: Here in this WebView example we show the use of web view in our application. To do that we display two buttons one is for displaying a web page and other is for displaying static HTML data in a web view. Below is the final output, download code and step by step explanation: Download Code? The Windows Community Toolkit provides a version of the UWP web view control that can be used in WPF and Windows Forms applications. This control embeds a view into your application that renders web content using the Microsoft Edge rendering engine. GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together. Launching Visual Studio. If nothing happens, download the GitHub extension for Visual Studio and try again. WebView Example in marketplace of vscode. Example.webview: Example: WebView; example.helloWorld.

  • Related Questions & Answers
  • Selected Reading
AndroidApps/ApplicationsMobile Development

This example demonstrates how do I create a WebView in android app.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to src/MainActivity.java

Step 4 − Add the following code to androidManifest.xml

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code.

-->

Note

WebView will eventually be replaced by WebView2 (currently in preview). Thus, the WebView has been deprecated within the Toolkit, but we are working on conveying requirements to the WebView2 team. If you would like to give feedback directly for WebView2, you can do so here on the Edge repository.

The WebView control shows web content in your Windows Forms or WPF desktop application. This is one of several wrapped Universal Windows Platform controls that are available for Windows Forms and WPF applications. For more information, see UWP controls in desktop applications.

This control uses the Microsoft Edge rendering engine (EdgeHTML) to embed a view that renders richly formatted HTML5 content from a remote web server, dynamically generated code, or content files.

Note

If you have feedback about this control, create a new issue in the Microsoft.Toolkit.Win32 repo and leave your comments there. If you prefer to submit your feedback privately, you can send it to XamlIslandsFeedback@microsoft.com. Your insights and scenarios are critically important to us.

About WebView controls

Here's where to find the Windows Forms and Windows Presentation Foundation (WPF) versions of the Microsoft Edge WebView control:

NuGet PackageNamespace
Windows FormsMicrosoft.Toolkit.Forms.UI.Controls.WebViewMicrosoft.Toolkit.Forms.UI.Controls
WPFMicrosoft.Toolkit.Wpf.UI.Controls.WebViewMicrosoft.Toolkit.Wpf.UI.Controls

(You can find additional related types (such as event args classes) in the Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT namespace.)

These controls wrap an instance of the WebViewControl class, and they provide a subset of members from that class. The WebViewControl is similar to the WebView class, but it is designed to run out of process in a desktop application (such as a WPF or Windows Forms application) and it supports a smaller set of members.

Unless specified otherwise in this article, the documentation for the WebViewControl class applies to the WPF and Windows Forms WebView controls. This article links to reference pages for the UWP WebViewControl class for more information about most members.

Prerequisites

✔️ Visual Studio 2017.

✔️ Windows 10 Insider Preview Build 17110 or a later release.

✔️ .NET Framework 4.6.2 or a later release.

✔️ Configure your application for high DPI support. To learn how, see this section of the guide.

Visual Studio Code Webview Example

Feature limitations

When compared to the UWP WebView control, the current release of the WPF and Windows Forms WebView control has some limitations. For the complete list of these limitations, see Known Issues of the WebView control for Windows Forms and WPF applications.

See also the FAQs section below for answers to common questions when WebView for Windows Forms and WPF applications.

Add the WebView control to the Visual Studio Toolbox for Windows Forms applications

For Visual Studio 15.8 and later:

  1. Install the Microsoft.Toolkit.Forms.UI.Controls.WebView NuGet package.

  2. Open the Toolbox in Visual Studio. The WebView control appears in the General section of the Toolbox and you can drag it directly the designer.

For earlier versions of Visual Studio:

  1. Install the Microsoft.Toolkit.Forms.UI.Controls.WebView NuGet package.

  2. Open the Toolbox in Visual Studio, right-click anywhere in the toolbox, and select the Choose Items option.

  3. In the .NET Framework Components tab of the Choose Toolbox Items dialog box, click Browse to locate the Microsoft.Toolkit.Forms.UI.Controls.WebView.dll in your NuGet package folder.

  4. Add Microsoft.Toolkit.Forms.UI.Controls.WebView.dll to the list of Toolbox controls, and then close the Choose Toolbox Items dialog box.

    The WebView control appears in the General section of the Toolbox.

    In Solution Explorer, the Microsoft.Toolkit.Forms.UI.Controls.WebView assembly appears in the References list.

Add the WebView control to the Visual Studio Toolbox for WPF applications

  1. Install the Microsoft.Toolkit.Wpf.UI.Controls.WebView NuGet package.

  2. Open the Toolbox in Visual Studio or Blend. The WebView control appears in the Windows Community Toolkit section of the Toolbox and you can drag it directly the designer. You can also create an instance of the WebView control in code, but we recommend that you do not add WebView controls to popup windows because support for that scenario will soon be disabled for security reasons.

Enable the WebView control to appear properly on high DPI displays

If users open your application on displays that have a high Dots Per Inch (DPI) displays, your WebView won't appear at the proper scale unless you configure your application first.

Configure a Windows Forms application

For guidance, see Configuring your Windows Forms app for high DPI support.

Configure a WPF application

Add the following XML to your application manifest file:

Add the following XML to your application configuration file:

Modify the appearance of a WebView

To constrain the display area, set the Width and Height properties.

This table contains links to each of these members.

MemberWindows Forms WebViewWPF WebView
Width propertyWidthWidth
Height propertyHeightHeight

Get the web page title

You can get the title of the HTML document currently displayed in the WebView by using the DocumentTitle property.

Input events and tab order

You can use the InvokeScriptAsync method with the JavaScript eval function to use the HTML event handlers, and use window.external.notify from the HTML event handlers to notify the application using the ScriptNotify event.

Navigate to content

The WebView control has several APIs for basic navigation: GoBack, GoForward, Stop, Refresh, CanGoBack, and CanGoForward. You can use these to add typical web browsing capabilities to your app.

Visual Studio Code Webview Example

To set the initial content of the the WebView control, you can set the Source property in code, XAML, or in the Properties window. You can also use the Navigate methods to load content in code. Here's an example.

Important

If calling Navigate() in code, you must wait until the control has loaded for the operation to complete successfully.

Visual Studio Sample Codes

Respond to navigation events

The WebView control provides several events that you can use to respond to navigation and content loading states. The events occur in the following order for the root web view content:

The NavigationStarting event is raised before the web view navigates to new content. You can cancel navigation in a handler for this event by setting the WebViewNavigationStartingEventArgs.Cancel property to true.

The ContentLoading is raised when the web view has started loading new content.

The DOMContentLoaded event is raised when the web view has finished parsing the current HTML content.

The NavigationCompleted event is raised when the web view has finished loading the current content or if navigation has failed. To determine whether navigation has failed, check the IsSuccess and WebErrorStatus properties of the event args.

Similar events occur in the same order for each iframe in the web view content:

  1. The FrameNavigationStarting event is raised before a frame in the web view navigates to new content.

  2. The FrameContentLoading event is raised when a frame in the web view has started loading new content.

  3. The FrameDOMContentLoaded event is raised when a frame in the web view has finished parsing its current HTML content.

  4. The FrameNavigationCompleted event is raised when a frame in the web view has finished loading its content.

Respond to potential problems

You can respond to potential problems with the content such as long running scripts, content that the WebView control can't load, and warnings of unsafe content.

Your app might appear unresponsive while scripts are running. The LongRunningScriptDetected event is raised periodically while the web view executes JavaScript. This provides you with an opportunity to interrupt the script. To determine how long the script has been running, check the ExecutionTime property of the WebViewControlLongRunningScriptDetectedEventArgs. To halt the script, set the event args StopPageScriptExecution property to true. The halted script will not execute again unless it is reloaded during a subsequent web view navigation.

The web view control cannot host arbitrary file types. When an attempt is made to load content that the web view can't host, the UnviewableContentIdentified event occurs. You can handle this event and notify the user.

Similarly, the UnsupportedUriSchemeIdentified event occurs when a URI scheme that's not supported is invoked in the web content, such as fbconnect:// or mailto://. You can handle this event to provide custom behavior instead of allowing the default system launcher to launch the URI.

Studio

The UnsafeContentWarningDisplayingEvent event occurs when the web view shows a warning page for content that was reported as unsafe by the SmartScreen Filter. If the user chooses to continue the navigation, subsequent navigation to the page will not display the warning nor fire the event.

Handle special cases for web view content

You can use the ContainsFullScreenElement property and ContainsFullScreenElementChanged event to detect, respond to, and enable full-screen experiences in web content, such as full-screen video playback.

For example, you might use the ContainsFullScreenElementChanged event to resize the web view to occupy the entire app view, or, as the following example illustrates, put a windowed app in full screen mode.

You can use the NewWindowRequested event to handle cases where hosted web content requests a new window, such as a popup window. You can use another WebView control to display the contents of the requested window.

Handle the PermissionRequested event to enable web features that require special capabilities. These currently include geolocation, IndexedDB storage, and user audio and video (for example, from a microphone or webcam).

In addition to the app handling the PermissionRequested event, the user will have to approve standard system dialogs for apps requesting location or media capabilities in order for these features to be enabled.

Here is an example of how an app would enable geolocation in a map from Bing:

If your app requires user input or other asynchronous operations to respond to a permission request, use the Defer method of WebViewControlPermissionRequest to create a WebViewControlDeferredPermissionRequest that can be acted upon at a later time.

Interact with web view content

You can interact with the content of the web view by using the InvokeScriptAsync method to invoke or inject script into the web view content, and the ScriptNotify event to get information back from the web view content.

To invoke JavaScript inside the web view content, use the InvokeScriptAsync method. The invoked script can return only string values.

For example, if the content of a web view named webView1 contains a function named setDate that takes 3 parameters, you can invoke it like this.

You can use InvokeScriptAsync with the JavaScript eval function to inject content into the web page.

Free Visual Studio Code Examples

Here, the text of a XAML text box (nameTextBox.Text) is written to a div in an HTML page hosted in webView1.

Scripts in the web view content can use window.external.notify with a string parameter to send information back to your app. To receive these messages, handle the ScriptNotify event.

Options for web content hosting

Visual

You can use the Settings property (of type WebViewControlSettings to control whether JavaScript and IndexedDB are enabled. For example, if you use a web view to display strictly static content, you might want to disable JavaScript for best performance.

Creating multiple web views in the same process

By default, the WebView is hosted outside of your application's process in a process called WWAHost. When using the designer or default constructor, each new WebView is created in a new WWAHost instance, with its own copy of state. To share session cookies and state, consider using the same WWAHost process to host your WebView.

For Windows Forms Applications

For example, if through the designer a WebView named webView1 is on Form1, you can create a new WebView that shares the same process and state with webView1 like this.

Form1.cs

For WPF Applications

Similar to the Windows Forms example, if through the designer a WebView is created named WebView1 on the Window, you can create a new WebView that shares the same process and state with WebView1 like this.

MainWindow.xaml

MainWindow.xaml.cs

Frequently Asked Questions (FAQs)

Visual Studio Web Application Examples

There’s WebBrowser, WebView, and WebViewControl. What’s the difference?

When people refer to a “web view” they either refer to the WebBrowser control in .NET, which uses the legacy Internet Explorer 'Trident' (MSHTML) engine, the Universal Windows Platform (UWP) WebView which uses the Microsoft Edge (EdgeHTML) engine on some versions of Windows and Trident on others, or the WebViewControl, which is a subset of the UWP WebView available for use in Windows Forms, WPF and other desktop (Win32) applications.

Is WebViewControl available on Windows Server?

No. Long-Term Servicing Channel (LTSC) versions of Windows, including Windows Server, don't include Microsoft Edge or many other UWP applications. These apps and their required services are frequently updated with new functionality and cannot be supported on systems running a LTSC operating system.

A future workaround might be to use Windows Virtual Desktop to run your WebViewControl application through a virtualized desktop on Windows 7, Windows 10 LTSC versions, and other environments where Microsoft Edge (and the WebViewControl) wouldn't otherwise be supported.

Are there samples?

Yes! Samples are available for Windows Forms, Windows Presentation Foundation, and C++ here:https://github.com/rjmurillo/webview-samples

Can I simply swap out the Internet Explorer WebBrowser for Microsoft Edge WebViewControl in my application?

No, the APIs differ significantly, as the WebViewControl represents several generations of browser development since the IE WebBrowser control was released.

Can I inject native objects into my WebViewControl content?

No. Neither the WebBrower (Internet Explorer) ObjectForScripting property nor the WebView (UWP) AddWebAllowedObject method are supported in WebViewControl. As a workaround, you can use window.external.notify/ ScriptNotify and JavaScript execution to communicate between the layers, for example: https://github.com/rjmurillo/WebView_AddAllowedWebObjectWorkaround

Can I host the UWP WebView in WPF or Windows Forms using XAML islands?

No. It is not possible to host the (full-featured) UWP WebView using XAML islands due to architectural and security constraints. The WebViewControl provided by Windows Community Toolkit is the recommended way of hosting a modern WebView control in desktop applications.

How do I debug WebViewControl?

To debug WebViewControl, download and install the standalone Microsoft Edge DevTools Preview app from the Microsoft Store. Once launched, the Local panel of the chooser will display all active EdgeHTML content processes, including open Edge browser tabs, Windows 10 web apps (WWAHost.exe processes), and webview controls.

Sample Project

You can see this in action in the Windows Community Toolkit Sample App.

Requirements

Device family.NET 4.6.2, Windows 10 (introduced v10.0.17110.0)
NamespaceWindows Forms: Microsoft.Toolkit.Forms.UI.Controls
WPF: Microsoft.Toolkit.Wpf.UI.Controls
NuGet packageWindows Forms: Microsoft.Toolkit.Forms.UI.Controls.WebView
WPF: Microsoft.Toolkit.Wpf.UI.Controls.WebView

C++ Visual Studio Code Example

API