Skip to content

Commit

Permalink
Updates for Win32, WPF, WinForms, UWP and WinUI3 sample apps from 130…
Browse files Browse the repository at this point in the history
….0.2839.0
  • Loading branch information
WebView2GithubBot committed Sep 16, 2024
1 parent d1cf80d commit 799322c
Show file tree
Hide file tree
Showing 7 changed files with 578 additions and 320 deletions.
5 changes: 3 additions & 2 deletions SampleApps/WebView2APISample/AppWindow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1429,11 +1429,11 @@ HRESULT AppWindow::OnCreateEnvironmentCompleted(
m_webViewEnvironment = environment;

if (m_webviewOption.entry == WebViewCreateEntry::EVER_FROM_CREATE_WITH_OPTION_MENU ||
m_creationModeId == IDM_CREATION_MODE_HOST_INPUT_PROCESSING
)
m_creationModeId == IDM_CREATION_MODE_HOST_INPUT_PROCESSING)
{
return CreateControllerWithOptions();
}

auto webViewEnvironment3 = m_webViewEnvironment.try_query<ICoreWebView2Environment3>();

if (webViewEnvironment3 && (m_dcompDevice || m_wincompCompositor))
Expand Down Expand Up @@ -1522,6 +1522,7 @@ HRESULT AppWindow::CreateControllerWithOptions()
}
}
//! [AllowHostInputProcessing]

if (m_dcompDevice || m_wincompCompositor)
{
//! [OnCreateCoreWebView2ControllerCompleted]
Expand Down
10 changes: 8 additions & 2 deletions SampleApps/WebView2APISample/WebView2APISample.vcxproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
Expand Down Expand Up @@ -391,6 +391,12 @@
<CopyFileToFolders Include="assets/ScenarioScreenCaptureIFrame2.html">
<DestinationFolders>$(OutDir)\assets</DestinationFolders>
</CopyFileToFolders>
<CopyFileToFolders Include="assets/ScenarioServiceWorkerSyncRegistrationManager.html">
<DestinationFolders>$(OutDir)\assets</DestinationFolders>
</CopyFileToFolders>
<CopyFileToFolders Include="assets/ScenarioServiceWorkerSyncRegistrationManagerServiceWorker.js">
<DestinationFolders>$(OutDir)\assets</DestinationFolders>
</CopyFileToFolders>
<CopyFileToFolders Include="assets/ScenarioSharedBuffer.html">
<DestinationFolders>$(OutDir)\assets</DestinationFolders>
</CopyFileToFolders>
Expand Down Expand Up @@ -489,4 +495,4 @@
<Error Condition="!Exists('..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220201.1\build\native\Microsoft.Windows.ImplementationLibrary.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Windows.ImplementationLibrary.1.0.220201.1\build\native\Microsoft.Windows.ImplementationLibrary.targets'))" />
<Error Condition="!Exists('..\packages\Microsoft.Web.WebView2.1.0.2783-prerelease\build\native\Microsoft.Web.WebView2.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Web.WebView2.1.0.2783-prerelease\build\native\Microsoft.Web.WebView2.targets'))" />
</Target>
</Project>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
<!DOCTYPE html>
<html>
<head>
<title>ScenarioServiceWorkerSyncRegistrationManager</title>
</head>

<body>
<h3>Periodic Background Sync Example</h3>
<h4>Registrations</h4>
<p id="periodic-sync-registrations"></p>
<div style="display: inline-block;">
<input type="text" placeholder="tag name" id="add-tag1">
<input type="text" placeholder="min interval" id="add-interval">
<button onclick="registeredSync('periodic-sync')"> Register </button>
</div>

<div>
<input type="text" placeholder="tag name" id="remove-tag1">
<button onclick="unregisterSync('periodic-sync')"> Unregister </button>
</div>

<div>
<input type="text" placeholder="tag name" id="dispatch-tag">
<button onclick="dispatchPeriodicSyncEvent()"> Dispatch Periodic Sync Task </button>
</div>

<div>
<button onclick="getSyncRegistrationsFromWebView2('periodic-sync')"> Get all Periodic Sync Registrations from WebView2</button>
</div>
<hr>

<h3>Background Sync Example</h3>
<h4>Registrations</h4>
<p id="background-sync-registrations"></p>
<div style="display: inline-block;">
<input type="text" placeholder="tag name" id="add-tag2">
<button onclick="registeredSync('background-sync')"> Register </button>
</div>

<div>
<input type="text" placeholder="tag name" id="remove-tag2">
<button onclick="unregisterSync('background-sync')"> Unregister </button>
</div>
<div>
<button onclick="getSyncRegistrationsFromWebView2('background-sync')"> Get all Background Sync Registrations from WebView2</button>
</div>

<script>
async function checkPermission() {
const status = await navigator.permissions.query({name: 'periodic-background-sync'});
if (status.state === 'granted') {
console.log("periodic-background-sync permission is granted");
} else {
console.log("periodic-background-sync permission is denied");
}
}

async function registerServiceWorker() {
if ('serviceWorker' in navigator) {
const registration = await navigator.serviceWorker.register(
'ScenarioServiceWorkerSyncRegistrationManagerServiceWorker.js', {
scope: './',
});
}
}

async function unregisterSync(type) {
const registration = await navigator.serviceWorker.ready;
let tag = document.getElementById("remove-tag1").value;
if (type === "periodic-sync") {
if ('periodicSync' in registration) {
await registration.periodicSync.unregister(tag);
}
} else if (type === "background-sync") {
tag = document.getElementById("remove-tag2").value;
if ('sync' in registration) {
await registration.sync.unregister(tag);
}
}
getSyncRegistrations(type);
}

async function registeredSync(type) {
const registration = await navigator.serviceWorker.ready;
let tag = document.getElementById("add-tag1").value;
if (type === "periodic-sync") {
const interval = document.getElementById("add-interval").value;
if ('periodicSync' in registration) {
try {
await registration.periodicSync.register(tag, { minInterval: interval });
} catch (error) {
console.log(error);
}
}
} else if (type === "background-sync") {
tag = document.getElementById("add-tag2").value;
if ('sync' in registration) {
try {
await registration.sync.register(tag);
} catch (error) {
console.log(error);
}
}
}
getSyncRegistrations(type);
}

async function getSyncRegistrations(type) {
const registration = await navigator.serviceWorker.ready;
let elementId = "periodic-sync-registrations";
let tags;
if (type === "background-sync") {
elementId = "background-sync-registrations";
tags = await registration.sync.getTags();
} else if (type === "periodic-sync") {
tags = await registration.periodicSync.getTags();
}
var registrations = "";
tags.forEach(tag => {
registrations += "Tag name: ";
registrations += tag;
registrations += " ";
});
if (registrations === "") {
registrations = "empty";
}
document.getElementById(elementId).textContent = registrations;
}

async function dispatchPeriodicSyncEvent() {
const registration = await navigator.serviceWorker.ready;
const tag = document.getElementById("dispatch-tag").value;
chrome.webview.postMessage(`DispatchPeriodicSyncEvent ${tag}`);
}

async function getSyncRegistrationsFromWebView2(type) {
if (type === "periodic-sync") {
chrome.webview.postMessage("GetPeriodicSyncRegistrations");
} else if ("background-sync") {
chrome.webview.postMessage("GetBackgroundSyncRegistrations");
}
}

checkPermission();
registerServiceWorker();
getSyncRegistrations("periodic-sync");
getSyncRegistrations("background-sync");

</script>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
function fetchAndCacheLatestNews() {
console.log("Fetched news from a server");
}

self.addEventListener("periodicsync", (event) => {
console.log("Periodic Sync Task Tag: " + event.tag + " executed");
event.waitUntil(fetchAndCacheLatestNews());
});

self.addEventListener("sync", (event) => {
console.log("Background Sync Task Tag: " + event.tag + " executed");
});
12 changes: 0 additions & 12 deletions SampleApps/WebView2WpfBrowser/App.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,5 @@ found in the LICENSE file.
xmlns:local="clr-namespace:WebView2WpfBrowser"
StartupUri="MainWindow.xaml">
<Application.Resources>
<!--
These CreationProperties use the Evergreen Edge executable that's installed on the machine.
-->
<wv2:CoreWebView2CreationProperties x:Key="EvergreenWebView2CreationProperties" />
<!--
If you want to use fixed version:
1) Navigate to https://developer.microsoft.com/en-us/microsoft-edge/webview2/
2) Choose "Fixed Version", select appropriate version and architecture and click download
3) Unzip the CAB file to a folder
4) Point that folder by `BrowserExecutableFolder` property
-->
<wv2:CoreWebView2CreationProperties x:Key="BYOWebView2CreationProperties" BrowserExecutableFolder="Replace this with BYO folder" />
</Application.Resources>
</Application>
35 changes: 22 additions & 13 deletions SampleApps/WebView2WpfBrowser/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ found in the LICENSE file.
Width="800"
>
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.New" Executed="NewCmdExecuted"/>
Expand Down Expand Up @@ -60,6 +61,7 @@ found in the LICENSE file.
<CommandBinding Command="{x:Static local:MainWindow.ClearServerCertificateErrorActionsCommand}" Executed="ClearServerCertificateErrorActionsCmdExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>
<CommandBinding Command="{x:Static local:MainWindow.SetDefaultDownloadPathCommand}" Executed="SetDefaultDownloadPathCmdExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>
<CommandBinding Command="{x:Static local:MainWindow.CreateDownloadsButtonCommand}" Executed="CreateDownloadsButtonCmdExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>
<CommandBinding Command="{x:Static local:MainWindow.ShowExtensionsWindowCommand}" Executed="ShowExtensionsWindowCmdExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>
<CommandBinding Command="{x:Static local:MainWindow.ToggleMuteStateCommand}" Executed="ToggleMuteStateCmdExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>
<CommandBinding Command="{x:Static local:MainWindow.PrintToPdfCommand}" Executed="PrintToPdfCmdExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>
<CommandBinding Command="{x:Static local:MainWindow.PinchZoomCommand}" Executed="PinchZoomCmdExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>
Expand Down Expand Up @@ -94,7 +96,8 @@ found in the LICENSE file.
<CommandBinding Command="{x:Static local:MainWindow.BrowserAcceleratorKeyEnabledCommand}" Executed="BrowserAcceleratorKeyEnabledCommandExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>

<CommandBinding Command="{x:Static local:MainWindow.CloseWebViewCommand}" Executed="CloseWebViewCommandExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>
<CommandBinding Command="{x:Static local:MainWindow.NewWebViewCommand}" Executed="NewWebViewCommandExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>
<CommandBinding Command="{x:Static local:MainWindow.NewWebViewCommand}" Executed="NewWebViewCommandExecuted"/>
<CommandBinding Command="{x:Static local:MainWindow.NewWebViewCompositionControlCommand}" Executed="NewWebViewCompositionControlCommandExecuted" CanExecute="EpxerimentalCmdsCanExecute"/>

<CommandBinding Command="{x:Static local:MainWindow.PermissionManagementCommand}" Executed="PermissionManagementExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>
<CommandBinding Command="{x:Static local:MainWindow.NonClientRegionSupportCommand}" Executed="NonClientRegionSupportCmdExecuted" CanExecute="CoreWebView2RequiringCmdsCanExecute"/>
Expand Down Expand Up @@ -136,8 +139,9 @@ found in the LICENSE file.
<!--TODO-->
</MenuItem>
<MenuItem Header="_Window">
<MenuItem Header="_Close WebView" Command="ApplicationCommands.Close"/>
<MenuItem Header="_New WebView" Command="{x:Static local:MainWindow.NewWebViewCommand}"/>
<MenuItem Header="_Close WebView2" Command="{x:Static local:MainWindow.CloseWebViewCommand}"/>
<MenuItem Header="_New WebView2" Command="{x:Static local:MainWindow.NewWebViewCommand}"/>
<MenuItem Header="_New WebView2CompositionControl" Command="{x:Static local:MainWindow.NewWebViewCompositionControlCommand}"/>
<MenuItem Header="_New Window" Command="ApplicationCommands.New"/>
<MenuItem Header="_New Window With Options" Command="{x:Static local:MainWindow.NewWindowWithOptionsCommand}"/>
<MenuItem Header="_Create New Thread" Command="{x:Static local:MainWindow.CreateNewThreadCommand}"/>
Expand Down Expand Up @@ -176,7 +180,7 @@ found in the LICENSE file.
<MenuItem Header="Toggle Non-Client Region Support" Command="{x:Static local:MainWindow.NonClientRegionSupportCommand}"/>
</MenuItem>
<MenuItem Header="_View">
<MenuItem Header="Toggle _Visibility" Name="webViewVisible" IsCheckable="True" IsChecked="True"/>
<MenuItem Header="Toggle _Visibility" Name="webViewVisible" IsCheckable="True" IsChecked="True" Checked="OnWebViewVisibleChecked" Unchecked="OnWebViewVisibleUnchecked"/>
<MenuItem Header="Suspend" Command="{x:Static local:MainWindow.SuspendCommand}"/>
<MenuItem Header="Resume" Command="{x:Static local:MainWindow.ResumeCommand}"/>
<MenuItem Header="_Increase Zoom" Command="NavigationCommands.IncreaseZoom"/>
Expand All @@ -188,6 +192,7 @@ found in the LICENSE file.
<MenuItem Header="Transparent" Command="{x:Static local:MainWindow.BackgroundColorCommand}" CommandParameter="Transparent"/>
</MenuItem>
<MenuItem Header="_Create Downloads Button" Command="{x:Static local:MainWindow.CreateDownloadsButtonCommand}"/>
<MenuItem Header="Show Extensions Manager" Command="{x:Static local:MainWindow.ShowExtensionsWindowCommand}" />
</MenuItem>
<MenuItem Header="S_cenario">
<MenuItem Header="Au_thentication" Command="{x:Static local:MainWindow.AuthenticationCommand}"/>
Expand Down Expand Up @@ -259,7 +264,7 @@ found in the LICENSE file.
<Button DockPanel.Dock="Left" Command="NavigationCommands.BrowseStop">Cancel</Button>
<Button DockPanel.Dock="Right" Command="NavigationCommands.GoToPage" CommandParameter="{Binding ElementName=url,Path=Text}">Go</Button>
<!-- We want the address bar to update based on the WebView's Source, but we don't want the WebView to navigate just from the user typing into the address bar. Therefore we use the OneWay binding mode. -->
<TextBox x:Name="url" Text="{Binding ElementName=webView,Path=Source,Mode=OneWay}">
<TextBox x:Name="url" Text="{Binding ElementName=webView2XamlElement,Path=Source,Mode=OneWay}">
<TextBox.InputBindings>
<KeyBinding Key="Return" Command="NavigationCommands.GoToPage" CommandParameter="{Binding ElementName=url,Path=Text}" />
</TextBox.InputBindings>
Expand All @@ -270,14 +275,18 @@ found in the LICENSE file.
<ImageBrush ImageSource="/assets/AppStartPageBackground.png" />
</Grid.Background>

<!-- If you want to use a specific version of WebView2 Runtime change EvergreenWebView2CreationProperties
to BYOWebView2CreationProperties and follow the steps in MainWindow.xaml
-->
<wv2:WebView2
x:Name="webView"
CreationProperties="{StaticResource EvergreenWebView2CreationProperties}"
Source="https://www.bing.com/"
/>
<wv2:WebView2 x:Name="webView2XamlElement">
<wv2:WebView2.CreationProperties>
<!--
By default, this CreationProperties uses the Evergreen WebView2 Runtime that's installed on the machine.
If you want to use a specific version of WebView2 Runtime, change BrowserExecutableFolder to point to the folder
with the runtime. https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#the-fixed-version-runtime-distribution-mode
-->
<wv2:CoreWebView2CreationProperties
BrowserExecutableFolder=""
AdditionalBrowserArguments="" />
</wv2:WebView2.CreationProperties>
</wv2:WebView2>
<!-- The control event handlers are set in code behind so they can be reused when replacing the control after
a WebView2 Runtime's browser process failure
-->
Expand Down
Loading

0 comments on commit 799322c

Please sign in to comment.