Example #1
0
        /// <summary>
        /// Navigates the webview to the application package
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadFromPackage_Click()
        {
            string url = "ms-appx-web:///html/html_example2.html";

            WebViewControl.Navigate(new Uri(url));
            rootPage.NotifyUser($"Navigated to {url}", NotifyType.StatusMessage);
        }
 private void Back_Click(object sender, RoutedEventArgs e)
 {
     if (WebViewControl.CanGoBack)
     {
         WebViewControl.GoBack();
     }
 }
Example #3
0
        private async void InvokeScript()
        {
            // Invoke the javascript function called 'doSomething' that is loaded into the WebView.
            try
            {
                string result = await WebViewControl.InvokeScriptAsync("doSomething", null);

                rootPage.NotifyUser($"Script returned \"{result}\"", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                string errorText = null;
                switch (ex.HResult)
                {
                case unchecked ((int)0x80020006):
                    errorText = "There is no function called doSomething";
                    break;

                case unchecked ((int)0x80020101):
                    errorText = "A JavaScript error or exception occured while executing the function doSomething";
                    break;

                case unchecked ((int)0x800a138a):
                    errorText = "doSomething is not a function";
                    break;

                default:
                    // Some other error occurred.
                    errorText = ex.Message;
                    break;
                }
                rootPage.NotifyUser(errorText, NotifyType.ErrorMessage);
            }
        }
Example #4
0
        private void LoadHTMLContent()
        {
            // WebViewControl.Navigate(new Uri("ms-appx-web:///html/BasicDirectionalNavigation.html"));
            WebViewControl.Navigate(new Uri("http://www.microsoft.com"));

            WebViewControl.Focus(FocusState.Programmatic);
        }
 /// <summary>
 /// Handler for the GoForward button
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void NavigateForward_Click()
 {
     if (WebViewControl.CanGoForward)
     {
         WebViewControl.GoForward();
     }
 }
        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();
        }
Example #7
0
        /// <summary>
        /// Captures the WebView into a bitmap.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void CaptureButton_Click()
        {
            InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
            await WebViewControl.CapturePreviewToStreamAsync(stream);

            // Scale the bitmap to the space available for the thumbnail image,
            // preserving aspect ratio.
            double thumbnailWidth       = ThumbnailImage.Width;
            double thumbnailHeight      = ThumbnailImage.Height;
            double webViewControlWidth  = WebViewControl.ActualWidth;
            double webViewControlHeight = WebViewControl.ActualHeight;

            if (thumbnailWidth == 0 || thumbnailHeight == 0 ||
                webViewControlWidth == 0 || webViewControlHeight == 0)
            {
                // Avoid 0x0 bitmaps, which cause all sorts of problems.
                return;
            }

            double       horizontalScale = thumbnailWidth / webViewControlWidth;
            double       verticalScale   = thumbnailHeight / webViewControlHeight;
            double       scale           = Math.Min(horizontalScale, verticalScale);
            int          width           = (int)(webViewControlWidth * scale);
            int          height          = (int)(webViewControlHeight * scale);
            BitmapSource thumbnailBitmap = await CreateScaledBitmapFromStreamAsync(width, height, stream);

            ThumbnailImage.Source = thumbnailBitmap;
        }
 /// <summary>
 /// Handler for the NavigateBackward button
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void NavigateBackward_Click()
 {
     if (WebViewControl.CanGoBack)
     {
         WebViewControl.GoBack();
     }
 }
Example #9
0
 /// <summary>
 /// 在 WebView 的历史记录中向前导航。
 /// </summary>
 private void ForwardAppBarButton_Click(object sender, RoutedEventArgs e)
 {
     if (WebViewControl.CanGoForward)
     {
         WebViewControl.GoForward();
     }
 }
Example #10
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;
        }
Example #11
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string url = "ms-appx-web:///Htm/About.html";

            WebViewControl.Navigate(new Uri(url));
            //rootPage.NotifyUser($"Navigated to {url}", NotifyType.StatusMessage);
        }
Example #12
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         webview?.Close();
         webview = null !;
     }
 }
Example #13
0
 /// <summary>
 /// 重写后退按钮按压事件以在 WebView (而不是应用程序)的返回栈中导航。
 /// </summary>
 private void MainPage_BackPressed(object sender, BackPressedEventArgs e)
 {
     if (WebViewControl.CanGoBack)
     {
         WebViewControl.GoBack();
         e.Handled = true;
     }
 }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            WebViewControl.Navigate(new Uri("http://www.microsoft.com"));

            // Register for the share event
            DataTransferManager.GetForCurrentView().DataRequested += DataTransferManager_DataRequested;
        }
        public IWebViewControlImpl MakeControlImpl(WebViewControl owner)
        {
            var shader         = _prototypeManager.Index <ShaderPrototype>("bgra");
            var shaderInstance = shader.Instance();
            var impl           = new ControlImpl(owner, shaderInstance);

            _dependencyCollection.InjectDependencies(impl);
            return(impl);
        }
        internal WebViewControlHost(WebViewControl webViewControl)
        {
            Verify.IsNotNull(webViewControl);

            _webViewControl = webViewControl ?? throw new ArgumentNullException(nameof(webViewControl));
            Process         = _webViewControl.Process;
            SubscribeEvents();
            SubscribeProcessExited();
        }
Example #17
0
        protected override Control CreateUIElement()
        {
            _webView = new WebViewControl();

            _webView.AddResourceRequestHandler(RequestHandler);
            _webView.AddBeforeBrowseHandler(BeforeBrowseHandler);

            return(_webView);
        }
Example #18
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var url = new Uri("https://www.bing.com/");

            if (e.Parameter is string)
            {
                Uri.TryCreate(e.Parameter.ToString(), UriKind.RelativeOrAbsolute, out url);
            }
            //var url = new Uri("https://cn.bing.com/images/");images/search?form=EDNTHT&mkt=zh-cn
            WebViewControl.Navigate(url);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // The 'Host' part of the URI for the ms-local-stream protocol is a combination of the package name
            // and an application-defined key, which identifies the specfic resolver.
            // Here, we use 'MyTag'.

            Uri url = WebViewControl.BuildLocalStreamUri("MyTag", "/default.html");

            // The resolver object needs to be passed in to the navigate call.
            WebViewControl.NavigateToLocalStreamUri(url, myResolver);
        }
Example #20
0
 private void NavigateToURL(MarkStringContent linkMark)
 {
     try
     {
         Uri targetUri = new Uri(linkMark.content);
         WebViewControl.Navigate(targetUri);
     }
     catch (UriFormatException)
     {
         System.Diagnostics.Debug.WriteLine("Address is invalid, try again.");
     }
 }
 /// <summary>
 /// This is the click handler for the "Go" button.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void GoButton_Click()
 {
     if (!pageIsLoading)
     {
         NavigateWebview(AddressBox.Text);
     }
     else
     {
         WebViewControl.Stop();
         pageIsLoading = false;
     }
 }
Example #22
0
        /*
         * private async void MainPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs e)
         * {
         *  DataRequestDeferral deferral = e.Request.GetDeferral();
         *  e.Request.Data.Properties.Title = "Golzin";
         *  Uri www = new Uri("http://viish.co.nf");
         *  e.Request.Data.SetText("Hello World, Golzin' your score: " + ant_value + "\n download in: " + www);
         *
         *
         *  StorageFile image = await GetFileFromBitmap(bmp);
         *
         *  if (image != null)
         *  {
         *      List<IStorageItem> storageItems = new List<IStorageItem>();
         *      storageItems.Add(image);
         *      e.Request.Data.SetStorageItems(storageItems);
         *
         *      //e.Request.Data.SetBitmap(RandomAccessStreamReference.CreateFromFile(image));
         *      //e.Request.Data.Properties.Thumbnail = RandomAccessStreamReference.CreateFromFile(image);
         *  }
         *  //else
         *  //{
         *  //    e.Request.Data.SetText(e.Request.Data.Properties.Description);
         *  //}
         *
         *
         *  deferral.Complete();
         * }
         *
         *
         *
         * private async Task<StorageFile> GetFileFromBitmap(WriteableBitmap writeableBitmp)
         * {
         *  string fileName = "MyImage.png";
         *
         *  //salvar arquivo no cell
         *  //StorageFolder localFolder = await KnownFolders.PicturesLibrary.CreateFolderAsync("golzin", CreationCollisionOption.ReplaceExisting);
         *  //StorageFile file = await localFolder.CreateFileAsync(fileName + ".png", CreationCollisionOption.GenerateUniqueName);
         *
         *  StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);//LocalFolder//TemporaryFolder
         *
         *  using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
         *  {
         *      BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
         *      Stream pixelStream = writeableBitmp.PixelBuffer.AsStream();
         *      byte[] pixels = new byte[pixelStream.Length];
         *      await pixelStream.ReadAsync(pixels, 0, pixels.Length);
         *      encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
         *                  (uint)writeableBitmp.PixelWidth,
         *                  (uint)writeableBitmp.PixelHeight,
         *                  96.0,
         *                  96.0,
         *                  pixels);
         *      await encoder.FlushAsync();
         *  }
         *
         *  return file;
         * }
         */


        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            WebViewControl.Navigate(HomeUri);

            StatusBar statusBar = StatusBar.GetForCurrentView();
            await statusBar.HideAsync();

            //await statusBar.ShowAsync();
            HardwareButtons.BackPressed += this.MainPage_BackPressed;
        }
 private void NavigateWebview()
 {
     try
     {
         Uri targetUri = new Uri("http://dev.dentall.site:8085/#/appointment");
         WebViewControl.Navigate(targetUri);
     }
     catch (UriFormatException ex)
     {
         // Bad address
     }
 }
 /// <summary>
 /// Helper to perform the navigation in webview
 /// </summary>
 /// <param name="url"></param>
 private void NavigateWebview(string url)
 {
     try
     {
         Uri targetUri = new Uri(url);
         WebViewControl.Navigate(targetUri);
     }
     catch (UriFormatException ex)
     {
         // Bad address
         AppendLog($"Address is invalid, try again. Error: {ex.Message}.");
     }
 }
 private void MainPage_BackRequested(object sender, BackRequestedEventArgs e)
 {
     if (WebViewControl.CanGoBack)
     {
         WebViewControl.GoBack();
         e.Handled = true;
     }
     else
     {
         App.Current.Exit();
         e.Handled = true;
     }
 }
Example #26
0
 private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
 {
     if (WebViewControl.CanGoBack) // Check if the back stack is not zero
     {
         WebViewControl.GoBack();  // Navigate one back in the back stack
     }
     else
     {
         //If back stack cannot go back for web content, then navigate away from the XAML page hosting the WebView
         Frame rootFrame = Window.Current.Content as Frame;
         rootFrame?.GoBack();
     }
 }
Example #27
0
        private async void WebViewControl_LoadCompleted(object sender, NavigationEventArgs e)
        {
            // var result = await GetKeywordsAS.Autosuggest();
            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Helpers/WebviewScript.js"));

            if (file != null)
            {
                string js = await FileIO.ReadTextAsync(file);

                //await GetContentFromFile(file);
                //eval函数大家都知道,就是执行一段字符串
                await WebViewControl.InvokeScriptAsync("eval", new string[] { js });
            }
        }
        /// <summary>
        /// Raised when the user initiates a Share operation.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        async void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            DataRequest request = args.Request;
            // We are going to use an async API to talk to the webview, so get a deferral to give
            // us time to generate the results.
            DataRequestDeferral deferral = request.GetDeferral();
            DataPackage         dp       = await WebViewControl.CaptureSelectedContentToDataPackageAsync();

            // Determine whether there was any selected content.
            bool hasSelection = false;

            try
            {
                hasSelection = (dp != null) && (dp.GetView().AvailableFormats.Count > 0);
            }
            catch (Exception ex)
            {
                switch (ex.HResult)
                {
                case unchecked ((int)0x80070490):
                    // Mobile does not generate a data package with AvailableFormats
                    // and results in an exception. Sorry. Handle the case by acting as
                    // if we had no selected content.
                    hasSelection = false;
                    break;

                default:
                    // All other exceptions are unexpected. Let them propagate.
                    throw;
                }
            }

            if (hasSelection)
            {
                // Webview has a selection, so we'll share its data package.
                dp.Properties.Title = "WebView sample selected content";
            }
            else
            {
                // No selection, so we'll share the url of the webview.
                dp = new DataPackage();
                dp.SetWebLink(WebViewControl.Source);
                dp.Properties.Title = "WebView sample page";
            }
            dp.Properties.Description = WebViewControl.Source.ToString();
            request.Data = dp;

            deferral.Complete();
        }
Example #29
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.Back)
            {
                if (localSettings.Values["NightScoutURL"] != null)
                {
                    NightScoutURL = localSettings.Values["NightScoutURL"].ToString();
                }
            }
            if (NightScoutURL != null)
            {
                WebViewControl.Navigate(new Uri(NightScoutURL));
                HardwareButtons.BackPressed += this.MainPage_BackPressed;
            }
        }
Example #30
0
        /// <summary>
        /// Navigates the webview to the local state directory
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void LoadFromLocalState_Click()
        {
            // Create a file in a subdirectory.
            // The ms-appdata protocol isolates top-level subdirectories from each other.

            StorageFolder stateFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("NavigateToState", CreationCollisionOption.OpenIfExists);

            StorageFile htmlFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///html/html_example2.html"));

            await htmlFile.CopyAsync(stateFolder, "test.html", NameCollisionOption.ReplaceExisting);

            string url = "ms-appdata:///local/NavigateToState/test.html";

            WebViewControl.Navigate(new Uri(url));
            rootPage.NotifyUser($"Navigated to {url}", NotifyType.StatusMessage);
        }