示例#1
0
        public EdgeHtmlWebview(WebviewBridge bridge)
        {
            this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge));

            var version = Native.GetOsVersion();

            supportsInitializeScript = version.MajorVersion >= 10 && version.BuildNumber >= 17763;

            var process = new WebViewControlProcess();
            var bounds  = new global::Windows.Foundation.Rect(Bounds.X, Bounds.Y, Bounds.Width, Bounds.Height);

            webview = process.CreateWebViewControlAsync(Handle.ToInt64(), bounds)
                      .AsTask()
                      .RunSyncWithPump();

            UpdateSize();

            if (supportsInitializeScript)
            {
                string initScript = Resources.GetInitScript("Windows");
                webview.AddInitializeScript(initScript);
            }

            webview.ScriptNotify += Webview_ScriptNotify;

            webview.NavigationStarting  += Webview_NavigationStarting;
            webview.NavigationCompleted += Webview_NavigationCompleted;
            Layout += (s, e) => UpdateSize();
        }
示例#2
0
        private void Init()
        {
            var process = new WebViewControlProcess();
            var bounds  = new Rect(Bounds.X, Bounds.Y, Bounds.Width, Bounds.Height);

            webview = process.CreateWebViewControlAsync(Handle.ToInt64(), bounds)
                      .AsTask()
                      .ConfigureAwait(false)
                      .GetAwaiter()
                      .GetResult();

            UpdateSize();

            webview.DefaultBackgroundColor         = ParseColor(config.BackgroundColor);
            webview.Settings.IsScriptNotifyAllowed = config.EnableScriptInterface;
            if (config.EnableScriptInterface)
            {
                webview.ScriptNotify += Webview_ScriptNotify;

                // TODO: needs Win10 1809 - 10.0.17763.0
                // webview.AddInitializeScript(initScript);
            }

            webview.NavigationCompleted += Webview_NavigationCompleted;
        }
示例#3
0
        private void Initialize()
        {
            Verify.AreEqual(_initializationState, InitializationState.IsInitializing);

            // This is causing freezing
            if (!DesignMode)
            {
                OSVersionHelper.ThrowIfBeforeWindows10April2018();

                if (!WebViewControlInitialized)
                {
                    if (Process == null)
                    {
                        // Was not injected via ctor, create using defaults
                        var options = new Win32.UI.Controls.Interop.WinRT.WebViewControlProcessOptions()
                        {
                            PrivateNetworkClientServerCapability =
                                (Win32.UI.Controls.Interop.WinRT.WebViewControlProcessCapabilityState)(_delayedPrivateNetworkEnabled
                                    ? WebViewControlProcessCapabilityState.Enabled
                                    : WebViewControlProcessCapabilityState.Disabled),
                            EnterpriseId = _delayedEnterpriseId
                        };

                        Process = new WebViewControlProcess(options);
                    }
                    else
                    {
                        Verify.IsNotNull(Process);

                        _delayedPrivateNetworkEnabled = Process.IsPrivateNetworkClientServerCapabilityEnabled;
                        _delayedEnterpriseId          = Process.EnterpriseId;
                    }

                    Verify.IsNotNull(Process);

                    _webViewControl = Process.CreateWebViewControlHost(Handle, ClientRectangle);
                    SubscribeEvents();

                    // Set values. They could have been changed in the designer
                    IsScriptNotifyAllowed = _delayedIsScriptNotifyAllowed;
                    IsIndexedDBEnabled    = _delayedIsIndexDbEnabled;
                    IsJavaScriptEnabled   = _delayedIsJavaScriptEnabled;

                    // This will cause a navigation
                    Source = _delayedSource;
                }
                else
                {
                    // Already provided control
                    SubscribeEvents();
                }

                _webViewControl.IsVisible = true;
            }

            _initializationState = InitializationState.IsInitialized;
        }
示例#4
0
        internal static Task <WebViewControlHost> CreateWebViewControlHostAsync(
            this WebViewControlProcess process,
            IntPtr hostWindowHandle,
            Rect bounds)
        {
            Verify.IsNotNull(process);
            Verify.IsFalse(hostWindowHandle == IntPtr.Zero);

            var rect = new Windows.Foundation.Rect(bounds.X, bounds.Y, bounds.Width, bounds.Height);

            return(process.CreateWebViewControlHostAsync(hostWindowHandle, rect));
        }
示例#5
0
        /// <summary>
        /// Creates a <see cref="IWebView"/> within the context of <paramref name="process"/>.
        /// </summary>
        /// <param name="process">An instance of <see cref="WebViewControlProcess" />.</param>
        /// <param name="hostWindowHandle">The host window handle.</param>
        /// <param name="bounds">A <see cref="Rect" /> containing numerical values that represent the location and size of the control.</param>
        /// <returns>An <see cref="IWebView" /> instance.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="hostWindowHandle"/> is equal to <see cref="IntPtr.Zero"/>, or
        /// <paramref name="process"/> is <see langword="null" />.
        /// </exception>
        internal static async Task <IWebView> CreateWebViewAsync(
            this WebViewControlProcess process,
            IntPtr hostWindowHandle,
            Rect bounds)
        {
            if (process is null)
            {
                throw new ArgumentNullException(nameof(process));
            }

            if (hostWindowHandle == IntPtr.Zero)
            {
                throw new ArgumentNullException(nameof(hostWindowHandle));
            }

            return(new WebView(await process.CreateWebViewControlHostAsync(hostWindowHandle, bounds).ConfigureAwait(false)));
        }
示例#6
0
        /// <summary>
        /// Creates a <see cref="IWebView"/> within the context of <paramref name="process"/>.
        /// </summary>
        /// <param name="process">An instance of <see cref="WebViewControlProcess" />.</param>
        /// <param name="hostWindowHandle">The host window handle.</param>
        /// <param name="bounds">A <see cref="Rect" /> containing numerical values that represent the location and size of the control.</param>
        /// <returns>An <see cref="IWebView" /> instance.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="hostWindowHandle"/> is equal to <see cref="IntPtr.Zero"/>, or
        /// <paramref name="process"/> is <see langword="null" />.
        /// </exception>
        internal static IWebView CreateWebView(
            this WebViewControlProcess process,
            IntPtr hostWindowHandle,
            Rect bounds)
        {
            if (process is null)
            {
                throw new ArgumentNullException(nameof(process));
            }

            if (hostWindowHandle == IntPtr.Zero)
            {
                throw new ArgumentNullException(nameof(hostWindowHandle));
            }

            return(new WebView(process.CreateWebViewControlHost(hostWindowHandle, bounds)));
        }
示例#7
0
        /// <summary>
        /// Creates a <see cref="IWebView"/> within the context of <paramref name="process"/> using the <paramref name="visual"/> to create a HWND.
        /// </summary>
        /// <param name="process">An instance of <see cref="WebViewControlProcess" />.</param>
        /// <param name="visual">A <see cref="Visual"/> instance in which to create a HWND.</param>
        /// <returns>An asynchronous operation that completes with a <see cref="IWebView"/>.</returns>
        /// <remarks>
        /// The bounds to draw the <see cref="WebView"/> are determined by the height and width of the <paramref name="visual"/>.
        /// </remarks>
        /// <seealso cref="CreateWebViewAsync(WebViewControlProcess,IntPtr,Rect)"/>
        internal static Task <IWebView> CreateWebViewAsync(this WebViewControlProcess process, Visual visual)
        {
            double width;
            double height;

            if (!visual.Dispatcher.CheckAccess())
            {
                width  = visual.Dispatcher.Invoke(() => (double)visual.GetValue(FrameworkElement.ActualWidthProperty));
                height = visual.Dispatcher.Invoke(() => (double)visual.GetValue(FrameworkElement.ActualHeightProperty));
            }
            else
            {
                width  = (double)visual.GetValue(FrameworkElement.ActualWidthProperty);
                height = (double)visual.GetValue(FrameworkElement.ActualHeightProperty);
            }

            return(process.CreateWebViewAsync(visual, new Rect(new Size(height, width))));
        }
示例#8
0
        /// <summary>
        /// Creates a <see cref="IWebView"/> within the context of <paramref name="process"/> using the <paramref name="visual"/> to create a HWND and within the specified <paramref name="bounds"/>.
        /// </summary>
        /// <param name="process">An instance of <see cref="WebViewControlProcess" />.</param>
        /// <param name="visual">A <see cref="Visual"/> instance in which to create a HWND.</param>
        /// <param name="bounds">A <see cref="Rect" /> containing numerical values that represent the location and size of the control.</param>
        /// <returns>An asynchronous operation that completes with a <see cref="IWebView"/>.</returns>
        internal static async Task <IWebView> CreateWebViewAsync(this WebViewControlProcess process, Visual visual, Rect bounds)
        {
            HwndSource sourceHwnd;

            if (!visual.Dispatcher.CheckAccess())
            {
                sourceHwnd = visual.Dispatcher.Invoke(() => (HwndSource)PresentationSource.FromVisual(visual));
            }
            else
            {
                sourceHwnd = (HwndSource)PresentationSource.FromVisual(visual);
            }

            Verify.IsNotNull(sourceHwnd);

            var webViewControlHost = await process.CreateWebViewControlHostAsync(sourceHwnd?.Handle ?? IntPtr.Zero, bounds);

            return(!visual.Dispatcher.CheckAccess()
                ? visual.Dispatcher.Invoke(() => new WebView(webViewControlHost))
                : new WebView(webViewControlHost));
        }
示例#9
0
 internal WebView(WebViewControlHost webViewControl)
     : this()
 {
     _webViewControl = webViewControl ?? throw new ArgumentNullException(nameof(webViewControl));
     _process        = webViewControl.Process;
 }
示例#10
0
 public WebView(WebViewControlProcess process)
     : this()
 {
     _process = process;
 }
示例#11
0
 protected override void When()
 {
     _webView2 = new UI.Controls.WinForms.WebView(WebViewControlProcess.CreateWebViewControlHost(Form.Handle, Form.ClientRectangle));
 }
示例#12
0
 public void ProcessIsNotNull()
 {
     WebViewControlProcess.ShouldNotBeNull();
 }
示例#13
0
 /// <summary>
 /// Creates a <see cref="IWebView"/> within the context of <paramref name="process"/> using the <paramref name="visual"/> to create a HWND.
 /// </summary>
 /// <param name="process">An instance of <see cref="WebViewControlProcess" />.</param>
 /// <param name="visual">A <see cref="Visual"/> instance in which to create a HWND.</param>
 /// <returns>An <see cref="IWebView"/> instance.</returns>
 /// <remarks>
 /// The bounds to draw the <see cref="WebView"/> are determined by the height and width of the <paramref name="visual"/>.
 /// </remarks>
 /// <seealso cref="CreateWebViewAsync(WebViewControlProcess,IntPtr,Rect)"/>
 internal static IWebView CreateWebView(this WebViewControlProcess process, Visual visual)
 {
     return(visual.Dispatcher.Invoke(() => process.CreateWebViewAsync(visual).GetAwaiter().GetResult()));
 }
示例#14
0
        private async void Form1_Load(object sender, EventArgs e)
        {
            var options = new WebViewControlProcessOptions
            {
                // Enable private network access to enable Enterprise SSO
                PrivateNetworkClientServerCapability = WebViewControlProcessCapabilityState.Enabled
            };
            var process = new WebViewControlProcess(options);
            var control = await process.CreateWebViewControlAsync(
                (long)this.Handle,
                new Windows.Foundation.Rect(0.0f, 0.0f, Width, Height));

            this.Layout += (o, a) =>
            {
                // This event is raised once at startup with the AffectedControl and AffectedProperty properties
                // on the LayoutEventArgs as null.
                if (a.AffectedControl != null && a.AffectedProperty != null)
                {
                    // Ensure that the affected property is the Bounds property to the control
                    if (a.AffectedProperty == nameof(this.Bounds))
                    {
                        // In a typical control the DisplayRectangle is the interior canvas of the control
                        // and in a scrolling control the DisplayRectangle would be larger than the ClientRectangle.
                        // However, that is abstracted from us in WebView so we need to synchronize the ClientRectangle
                        // and permit WebView to handle scrolling based on the new viewport
                        var rect = new Rect(
                            this.ClientRectangle.X,
                            this.ClientRectangle.Y,
                            this.ClientRectangle.Width,
                            this.ClientRectangle.Height);

                        control.Bounds = rect;
                    }
                }
            };

            control.ContainsFullScreenElementChanged += (o, a) =>
            {
                void EnterFullScreen()
                {
                    this.WindowState     = FormWindowState.Normal;
                    this.FormBorderStyle = FormBorderStyle.None;
                    this.WindowState     = FormWindowState.Maximized;
                }

                void LeaveFullScreen()
                {
                    this.FormBorderStyle = FormBorderStyle.Sizable;
                    this.WindowState     = FormWindowState.Normal;
                }

                // Toggle
                this.isFullScreen = !this.isFullScreen;

                if (this.isFullScreen)
                {
                    EnterFullScreen();
                }
                else
                {
                    LeaveFullScreen();
                }
            };

            control.ScriptNotify += (o, a) => { MessageBox.Show(a.Value, a.Uri?.ToString() ?? string.Empty); };

            control.NavigationCompleted += (o, a) =>
            {
                this.Text = o.DocumentTitle;
                if (!a.IsSuccess)
                {
                    MessageBox.Show(
                        $"Could not navigate to {a.Uri}",
                        $"Error: {a.WebErrorStatus}",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
            };

            control.NavigationStarting += (o, a) =>
            {
                this.Text = "Navigating " + (a.Uri?.ToString() ?? string.Empty);
            };

            control.PermissionRequested += (o, a) =>
            {
                if (a.PermissionRequest.State == WebViewControlPermissionState.Allow)
                {
                    return;
                }

                var msg = $"Allow {a.PermissionRequest.Uri.Host} to access {a.PermissionRequest.PermissionType}?";

                var response = MessageBox.Show(msg, "Permission Request", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

                if (response == DialogResult.Yes)
                {
                    if (a.PermissionRequest.State == WebViewControlPermissionState.Defer)
                    {
                        o.GetDeferredPermissionRequestById(a.PermissionRequest.Id, out var permission);
                        permission?.Allow();
                    }
                    else
                    {
                        a.PermissionRequest.Allow();
                    }
                }
                else
                {
                    if (a.PermissionRequest.State == WebViewControlPermissionState.Defer)
                    {
                        o.GetDeferredPermissionRequestById(a.PermissionRequest.Id, out var permission);
                        permission?.Deny();
                    }
                    else
                    {
                        a.PermissionRequest.Deny();
                    }
                }
            };

            control.Navigate(new Uri("http://bing.com"));
        }
示例#15
0
        public static async Task <WebAuthenticationResult> AuthenticateAsync(
            Uri requestUri, Uri callbackUri, Window parentWindow)
        {
            var            webViewControlProcess = new WebViewControlProcess();
            WebViewControl webViewControl        = null;

            var webViewWindow = new WebAuthenticationWindow();

            webViewWindow.Owner = parentWindow;

            // Response details
            string responseData = "";
            uint   responseCode = 0;
            var    status       = WebAuthenticationStatus.Success;

            webViewWindow.Loaded += async(_, __) =>
            {
                await Task.Delay(200);

                webViewControl = await webViewControlProcess.CreateWebViewControlAsync(
                    new WindowInteropHelper(webViewWindow).Handle.ToInt64(),
                    new Windows.Foundation.Rect(0, 0, webViewWindow.ActualWidth, webViewWindow.ActualHeight));

                webViewControl.NavigationStarting += (s, e) =>
                {
                    // Check for the Uri first -- localhost will give a 404
                    // but we might already have the data we want
                    if (e.Uri.ToString().StartsWith(callbackUri.ToString()))
                    {
                        responseData = e.Uri.ToString();
                        webViewWindow.DialogResult = true;
                    }
                };

                webViewControl.NavigationCompleted += (s, e) =>
                {
                    if (!e.IsSuccess)
                    {
                        webViewWindow.DialogResult = false;
                        responseCode = (uint)e.WebErrorStatus;
                    }
                };

                webViewControl.Navigate(requestUri);
            };

            var dialogResult = await ShowDialogAsync(webViewWindow);

            if (dialogResult.HasValue)
            {
                status = dialogResult.Value ? WebAuthenticationStatus.Success : WebAuthenticationStatus.Error;
            }
            else
            {
                status = WebAuthenticationStatus.Canceled;
            }

            webViewControlProcess.Terminate();

            return(new WebAuthenticationResult(responseData, responseCode, status));
        }