Esempio n. 1
0
 public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
 {
     ContextBridge.BridgeEvaluator(Element, message.Body.ToString(), delegate(string result)
     {
         Control.EvaluateJavaScript((NSString)result, GetJavascriptEvaluationResultHandler());
     });
 }
		protected override void OnElementChanged(ElementChangedEventArgs<HybridWebView> e)
		{
			
			base.OnElementChanged(e);
			if (Control == null)
			{
				
				userController = new WKUserContentController();
				var config = new WKWebViewConfiguration { UserContentController = userController };
				var webView = new WKWebView(Frame, config);

				var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
				userController.AddUserScript(script);
				userController.AddScriptMessageHandler(this, "invokeAction");
				SetNativeControl(webView);
				if (e.OldElement != null)
				{
					userController.RemoveAllUserScripts();
					userController.RemoveScriptMessageHandler("invokeAction");
					var hybridWebView = e.OldElement as HybridWebView;
					hybridWebView.Cleanup();
				}
				if (e.NewElement != null)
				{
					var a = this.Control.Url;
					Control.AccessibilityViewIsModal = true;

					NSMutableUrlRequest sendData = new NSMutableUrlRequest(new NSUrl(Element.Uri));
					Control.LoadRequest(sendData);

				}
			}
		}
Esempio n. 3
0
        protected override void OnElementChanged(ElementChangedEventArgs <BlazorWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null && e.NewElement != null)
            {
                userController = new WKUserContentController();
                //var script = new WKUserScript(new NSString(ContextBridgeHelper.GetInjectableJavascript(false)), WKUserScriptInjectionTime.AtDocumentEnd, false);
                //userController.AddUserScript(script);
                userController.AddScriptMessageHandler(this, "invokeAction");

                var config = new WKWebViewConfiguration {
                    UserContentController = userController, Preferences = new WKPreferences()
                    {
                        JavaScriptCanOpenWindowsAutomatically = false,
                        JavaScriptEnabled = true
                    }
                };
                var webView = new WKWebView(Frame, config);
                webView.NavigationDelegate = new WebNavigationDelegate(this);
                SetNativeControl(webView);
            }

            if (e.OldElement != null)
            {
                userController.RemoveAllUserScripts();
                userController.RemoveScriptMessageHandler("invokeAction");
            }
            if (e.NewElement != null)
            {
                Control.LoadRequest(new NSUrlRequest(new NSUrl(WebApplicationFactory.GetBaseURL())));
            }
        }
Esempio n. 4
0
        private void SetupControl()
        {
            _navigationDelegate = new HybridWebViewNavigationDelegate(this);
            _contentController  = new WKUserContentController();
            _contentController.AddScriptMessageHandler(this, "invokeAction");
            _configuration = new WKWebViewConfiguration
            {
                UserContentController     = _contentController,
                AllowsInlineMediaPlayback = true
            };


            var wkWebView = new WKWebView(Frame, _configuration)
            {
                Opaque             = false,
                UIDelegate         = this,
                NavigationDelegate = _navigationDelegate,
            };


            HybridWebViewControl.CallbackAdded += OnCallbackAdded;

            SetNativeControl(wkWebView);
            SetUserAgent();
            OnControlChanged?.Invoke(this, wkWebView);
        }
        private void SetupControl(FormsWebView element)
        {
            WebViewControlDelegate.OnNavigationRequestedFromUser += OnUserNavigationRequested;
            WebViewControlDelegate.OnInjectJavascriptRequest     += OnInjectJavascriptRequested;
            WebViewControlDelegate.OnActionAdded += OnActionAdded;

            UserController = new WKUserContentController();
            UserController.AddScriptMessageHandler(this, "invokeAction");

            NavigationDelegate   = new FormsWKNavigationDelegate(this, element);
            WebViewConfiguration = new WKWebViewConfiguration {
                UserContentController = UserController
            };

            var webView = new WKWebView(Frame, WebViewConfiguration);

            webView.UIDelegate         = this;
            webView.NavigationDelegate = NavigationDelegate;

            UriBase = NSBundle.MainBundle.ResourcePath;

            OnControlChanging?.Invoke(this, Element, Control);
            SetNativeControl(webView);
            OnControlChanged?.Invoke(this, Element, Control);
        }
        protected override void OnElementChanged(ElementChangedEventArgs <GalleyBrowserControl> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                _userController = new WKUserContentController();
                var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
                _userController.AddUserScript(script);
                _userController.AddScriptMessageHandler(this, GalleyHtmlConstants.InvokeSharpCodeActionName);

                var config = new WKWebViewConfiguration {
                    UserContentController = _userController
                };
                var webView = new WKWebView(Frame, config)
                {
                    NavigationDelegate = new CustomWKNavigationDelegate()
                };
                SetNativeControl(webView);
                OnElementPropertyChanged(nameof(Element.Uri));
                OnElementPropertyChanged(nameof(Element.Html));
                OnJavaScriptInvoked(Element.JavaScriptFunction);
            }
            if (e.OldElement != null)
            {
                _userController.RemoveAllUserScripts();
                _userController.RemoveScriptMessageHandler(GalleyHtmlConstants.InvokeSharpCodeActionName);
                e.OldElement.JavaScriptInvoked -= OnJavaScriptInvoked;
            }
            if (e.NewElement != null)
            {
                e.NewElement.JavaScriptInvoked += OnJavaScriptInvoked;
            }
        }
Esempio n. 7
0
        public Xamarin.Forms.View CreateWebView()
        {
            var preferences = new WKPreferences()
            {
                JavaScriptEnabled = true,
                JavaScriptCanOpenWindowsAutomatically = false
            };
            var configuration = new WKWebViewConfiguration()
            {
                UserContentController = userContentController = new WKUserContentController()
            };
            var helper         = new Ao3TrackHelper(this);
            var messageHandler = new Ao3TrackReader.iOS.ScriptMessageHandler(helper);

            userContentController.AddScriptMessageHandler((WKScriptMessageHandler)messageHandler, "ao3track");
            this.helper = helper;

            configuration.Preferences = preferences;

            webView = new WKWebView(configuration)
            {
                NavigationDelegate = new NavigationDelegate(this)
            };

            webView.FocuseChanged += WebView_FocusChange;

            var xview = webView.ToView();

            xview.SizeChanged += Xview_SizeChanged;

            return(xview);
        }
        protected override void OnElementChanged(ElementChangedEventArgs <HybridWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                userController = new WKUserContentController();
                var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, true);
                var api    = new WKUserScript(new NSString(Element.APIJS), WKUserScriptInjectionTime.AtDocumentStart, true);
                // var apiSetup = new WKUserScript(new NSString(APISetup), WKUserScriptInjectionTime.AtDocumentStart, true);
                userController.AddUserScript(script);
                userController.AddUserScript(api);
                // userController.AddUserScript(apiSetup);

                userController.AddScriptMessageHandler(this, "invokeAction");


                var config = new WKWebViewConfiguration {
                    UserContentController = userController
                };
                WKJavascriptEvaluationResult handler = (NSObject result, NSError err) => {
                    if (err != null)
                    {
                        System.Console.WriteLine(err);
                    }
                    if (result != null)
                    {
                        System.Console.WriteLine(result);
                    }
                };
                var webView = new WKWebView(Frame, config);
                // var js = (NSString)"SetupAPI()";
                //webView.EvaluateJavaScript(js, null);
                webView.Configuration.Preferences.SetValueForKey(NSObject.FromObject(true), new NSString("allowFileAccessFromFileURLs"));
                webView.CustomUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1";
                webView.SizeToFit();


                SetNativeControl(webView);
            }
            if (e.OldElement != null)
            {
                userController.RemoveAllUserScripts();
                userController.RemoveScriptMessageHandler("invokeAction");
                userController.RemoveScriptMessageHandler("Terminate");
                userController.RemoveScriptMessageHandler("Commit");
                var hybridWebView = e.OldElement as HybridWebView;
                hybridWebView.Cleanup();
            }
            if (e.NewElement != null)
            {
                var docsDir      = NSFileManager.DefaultManager.GetUrl(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, null, true, out var error);
                var data         = NSUrl.FromFilename(Path.Combine(docsDir.Path, Element.iOSPath));
                var frame        = NSUrl.FromFilename(Path.Combine(docsDir.Path, "Courses/index.htm"));
                var htmlString   = new NSString(Element.Source);
                var content      = NSUrl.FromFilename(Path.Combine(docsDir.Path, "Courses"));
                var contentFrame = NSUrl.FromFilename(Path.Combine(docsDir.Path));
                Control.LoadFileUrl(data, content);
            }
        }
Esempio n. 9
0
        void SetupControl(FormsWebView element)
        {
            WebViewControlDelegate.OnNavigationRequestedFromUser += OnUserNavigationRequested;
            WebViewControlDelegate.OnInjectJavascriptRequest     += OnInjectJavascriptRequested;
            WebViewControlDelegate.OnStackNavigationRequested    += OnStackNavigationRequested;
            WebViewControlDelegate.OnActionAdded += OnActionAdded;

            UserController = new WKUserContentController();
            UserController.AddScriptMessageHandler(this, "invokeAction");

            NavigationDelegate   = new FormsWKNavigationDelegate(this, element);
            WebViewConfiguration = new WKWebViewConfiguration {
                UserContentController = UserController
            };

            var webView = new WKWebView(Frame, WebViewConfiguration);

            webView.Opaque             = false;
            webView.UIDelegate         = this;
            webView.NavigationDelegate = NavigationDelegate;
            webView.ScalesPageToFit    = true;

            OnControlChanging?.Invoke(this, Element, Control);
            SetNativeControl(webView);
            OnControlChanged?.Invoke(this, Element, Control);
        }
Esempio n. 10
0
        public static WebViewWrapper WrapperFactory(MusicProvider provider)
        {
            WKUserContentController controller = new WKUserContentController();

            controller.AddUserScript(
                new WKUserScript(new NSString(provider.EventsJs), WKUserScriptInjectionTime.AtDocumentEnd, false)
                );
            controller.AddScriptMessageHandler(Container.WKScriptMessageHandler, "playbackState");

            WKWebViewConfiguration config = new WKWebViewConfiguration
            {
                UserContentController = controller
            };

            config.Preferences.SetValueForKey(NSObject.FromObject(true), new NSString("developerExtrasEnabled"));

            var webView = new WKWebView(new CGRect(0, 0, 100, 100), config)
            {
                CustomUserAgent = "Mozilla/5.0 " +
                                  "(Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 " +
                                  "(KHTML, like Gecko) Version/12.0 Safari/605.1.15",
                AutoresizingMask   = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable,
                NavigationDelegate = new NavigationDelegate()
            };

            webView.TranslatesAutoresizingMaskIntoConstraints = false;
            var req = new NSUrlRequest(new NSUrl(provider.Url));

            webView.LoadRequest(req);

            return(new WebViewWrapper(webView, provider));
        }
Esempio n. 11
0
        protected override void OnElementChanged(ElementChangedEventArgs <customWebView> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null)
            {
                e.OldElement.SetTextScaned = null;
                e.OldElement.DoSearch      = null;
                e.OldElement.Observe       = null;
            }
            if (e.NewElement != null)
            {
                if (Control == null)
                {
                    userController = new WKUserContentController();
                    var config = new WKWebViewConfiguration {
                        UserContentController = userController
                    };
                    wkWebView = new WKWebView(Frame, config);
                    SetNativeControl(wkWebView);

                    buttonPressedScriptHandler = new WebViewButtonPressedHandler(e.NewElement);
                    userController.AddScriptMessageHandler(buttonPressedScriptHandler, "ButtonPressedScriptHandler");
                }

                e.NewElement.SetTextScaned = SetSearchText;
                e.NewElement.DoSearch      = DoSearch;
                e.NewElement.Observe       = Observe;

                if (e.NewElement.Source != null)
                {
                    Control.LoadRequest(new NSUrlRequest(new NSUrl((Element.Source as UrlWebViewSource)?.Url)));
                }
            }
        }
        protected override void OnElementChanged(ElementChangedEventArgs <HybridWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                userController = new WKUserContentController();
                var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
                userController.AddUserScript(script);
                userController.AddScriptMessageHandler(this, "invokeAction");

                var config = new WKWebViewConfiguration {
                    UserContentController = userController
                };
                var webView = new WKWebView(Frame, config);
                SetNativeControl(webView);
            }
            if (e.OldElement != null)
            {
                userController.RemoveAllUserScripts();
                userController.RemoveScriptMessageHandler("invokeAction");
                var hybridWebView = e.OldElement as HybridWebView;
                hybridWebView.Cleanup();
            }
            if (e.NewElement != null)
            {
                string fileName = Path.Combine(NSBundle.MainBundle.BundlePath, string.Format("Content/{0}", Element.Uri));
                Control.LoadRequest(new NSUrlRequest(new NSUrl(fileName, false)));
            }
        }
Esempio n. 13
0
        public override async void ViewDidLoad()
        {
            base.ViewDidLoad();

            var scriptDelegate = new WkPostMessageScriptMessageHandler(this);

            WKUserContentController contentController = new WKUserContentController();

            contentController.AddScriptMessageHandler(scriptDelegate, "sendToApp");
            contentController.AddScriptMessageHandler(scriptDelegate, "onHtmlLoadCompleted");

            WKWebViewConfiguration config = new WKWebViewConfiguration();

            config.UserContentController = contentController;

            wkWebview = new WKWebView(webViewContainer.Frame, config);
            webViewContainer.AddSubview(wkWebview);

            var wkUIDelegate = new PostMessageWkWebViewDelegate();

            wkUIDelegate.ParentController = this;
            wkWebview.UIDelegate          = wkUIDelegate;

            var navigationDelegate = new PostMessageNavigationDelegate();

            wkWebview.NavigationDelegate = navigationDelegate;

            activityIndicator.Hidden = true;

            await SetManager();
        }
        void SetupControl()
        {
            _navigationDelegate = new FormsNavigationDelegate(this);
            _contentController  = new WKUserContentController();
            _contentController.AddScriptMessageHandler(this, "invokeAction");
            _configuration = new WKWebViewConfiguration {
                UserContentController = _contentController,
            };
            _configuration.ProcessPool = _processPool;

            var wkWebView = new WKWebView(Frame, _configuration)
            {
                Opaque             = false,
                UIDelegate         = this,
                NavigationDelegate = _navigationDelegate,
            };

            FormsWebView.CallbackAdded += OnCallbackAdded;

            try {
                //Autoresize after rotation. Wrapped in try catch with no handling since untested
                wkWebView.ContentMode      = UIViewContentMode.ScaleAspectFit;
                wkWebView.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
                wkWebView.SizeToFit();

                if (wkWebView.ScrollView != null)
                {
                    wkWebView.ScrollView.Bounces = false;
                }
            } catch { /*Do nothing right now*/ }


            SetNativeControl(wkWebView);
            OnControlChanged?.Invoke(this, wkWebView);
        }
Esempio n. 15
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var userController = new WKUserContentController();

            var scriptImage    = new WKUserScript(new NSString(JavaScriptFunctionForImage), WKUserScriptInjectionTime.AtDocumentEnd, false);
            var scriptVideo    = new WKUserScript(new NSString(JavaScriptFunctionForVideo), WKUserScriptInjectionTime.AtDocumentEnd, false);
            var scriptPDF      = new WKUserScript(new NSString(JavaScriptFunctionForPDF), WKUserScriptInjectionTime.AtDocumentEnd, false);
            var scriptAllFiles = new WKUserScript(new NSString(JavaScriptFunctionForDownloadAll), WKUserScriptInjectionTime.AtDocumentEnd, false);
            var scriptGetURL   = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);

            userController.AddUserScript(scriptGetURL);
            userController.AddScriptMessageHandler(this, "callBack");

            webView = new WKWebView(new CoreGraphics.CGRect(0, 0, 375, 667), new WKWebViewConfiguration()
            {
                UserContentController = userController
            });
            webView.UIDelegate         = this;
            webView.NavigationDelegate = this;
            View.AddSubview(webView);
            webView.LoadRequest(new NSUrlRequest(url));
            StartActivityIndicatorWithText("Loading...", new CoreGraphics.CGRect(0, 0, 375, 667));
        }
        void SetupControl()
        {
            _navigationDelegate = new FormsNavigationDelegate(this);
            _contentController  = new WKUserContentController();
            _contentController.AddScriptMessageHandler(this, "invokeAction");
            _configuration = new WKWebViewConfiguration {
                UserContentController = _contentController
            };

            if (Element.ApplicationNameForUserAgent != null && Element.ApplicationNameForUserAgent.Length > 0)
            {
                _configuration.ApplicationNameForUserAgent = Element.ApplicationNameForUserAgent;
            }

            var wkWebView = new WKWebView(Frame, _configuration)
            {
                Opaque             = false,
                UIDelegate         = this,
                NavigationDelegate = _navigationDelegate
            };

            FormsWebView.CallbackAdded += OnCallbackAdded;

            SetNativeControl(wkWebView);
            OnControlChanged?.Invoke(this, wkWebView);
        }
Esempio n. 17
0
        public HybridWebViewRenderer(WKWebViewConfiguration config) : base(config)
        {
            userController = config.UserContentController;
            var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);

            userController.AddUserScript(script);
        }
Esempio n. 18
0
 /// <summary>
 /// Produces PNG from HTML
 /// </summary>
 /// <param name="taskCompletionSource"></param>
 /// <param name="html"></param>
 /// <param name="fileName"></param>
 public void ToPng(TaskCompletionSource <ToFileResult> taskCompletionSource, string html, string fileName, int width)
 {
     if (NSProcessInfo.ProcessInfo.IsOperatingSystemAtLeastVersion(new NSOperatingSystemVersion(11, 0, 0)))
     {
         string                  jScript       = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
         WKUserScript            wkUScript     = new WKUserScript((NSString)jScript, WKUserScriptInjectionTime.AtDocumentEnd, true);
         WKUserContentController wkUController = new WKUserContentController();
         wkUController.AddUserScript(wkUScript);
         var configuration = new WKWebViewConfiguration
         {
             UserContentController = wkUController
         };
         var webView = new WKWebView(new CGRect(0, 0, width, width), configuration)
         {
             UserInteractionEnabled = false,
             BackgroundColor        = UIColor.White
         };
         webView.NavigationDelegate = new WKNavigationCompleteCallback(fileName, new WebViewToPngSize(width), null, taskCompletionSource, NavigationComplete);
         webView.LoadHtmlString(html, null);
     }
     else
     {
         taskCompletionSource.SetResult(new ToFileResult(true, "PNG output not available prior to iOS 11"));
     }
 }
 /// <summary>
 /// Implements a method from interface <see cref="IWKScriptMessageHandler"/>.
 /// </summary>
 /// <param name="userContentController">User controller sending the message.</param>
 /// <param name="message">The message being sent.</param>
 public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
 {
     if (this.Element != null)
     {
         this.Element.MessageReceived(message.Body.ToString());
     }
 }
 public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
 {
     InvokeOnMainThread(() => {
         ctx.ChangeTextAsync(0, message.Body.ToString());
         ctx.ChangeTextAsync(1000, "Ready.");
     });
 }
Esempio n. 21
0
 public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
 {
     if (Element != null)
     {
         Element.InvokeEvent(WebViewEventType.JavascriptCallback, new JavascriptResponseDelegate(Element, message.Body.ToString()));
     }
 }
Esempio n. 22
0
        protected override void OnElementChanged(ElementChangedEventArgs <CustomWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                userController = new WKUserContentController();
                var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
                userController.AddUserScript(script);
                userController.AddScriptMessageHandler(this, "invokeAction");

                var config = new WKWebViewConfiguration {
                    UserContentController = userController
                };
                var webView = new WKWebView(Frame, config);
                SetNativeControl(webView);
            }

            if (e.OldElement != null)
            {
                userController.RemoveAllUserScripts();
                userController.RemoveScriptMessageHandler("invokeAction");

                var customWebView = e.OldElement as CustomWebView;
                customWebView.Cleanup();
            }

            if (e.NewElement != null)
            {
                System.Diagnostics.Debug.WriteLine(Element.Uri);
                Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Uri)));
            }
        }
Esempio n. 23
0
        protected override void OnElementChanged(ElementChangedEventArgs <ExtendedWebView> e)
        {
            try
            {
                view = (ExtendedWebView)Element;
                string url = view.Source.GetValue(UrlWebViewSource.UrlProperty).ToString();

                //The width=device-width part sets the width of the page to follow the screen-width of the device
                //(which will vary depending on the device)
                string javaScript = @"var meta = document.createElement('meta');
                                       meta.setAttribute('name', 'viewport');
                                       meta.setAttribute('content', 'width=device-width');
                                       document.getElementsByTagName('head')[0].appendChild(meta);";

                WKUserScript            wkUScript     = new WKUserScript((NSString)javaScript, WKUserScriptInjectionTime.AtDocumentEnd, true);
                WKUserContentController wkUController = new WKUserContentController();
                wkUController.AddUserScript(wkUScript);

                WKWebViewConfiguration wkWebConfig = new WKWebViewConfiguration();
                wkWebConfig.UserContentController = wkUController;
                _wkWebView = new WKWebView(Frame, wkWebConfig);
                _wkWebView.ScrollView.ScrollEnabled = true;
                _wkWebView.NavigationDelegate       = new HybridWebviewDelegate();
                _wkWebView.LoadRequest(new NSUrlRequest(new NSUrl(url)));

                SetNativeControl(_wkWebView);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 24
0
        protected override void OnElementChanged(ElementChangedEventArgs <HybridWebView> e)
        {
            if (Control == null)
            {
                userController = new WKUserContentController();
                var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentStart, false);
                userController.AddUserScript(script);
                userController.AddScriptMessageHandler(this, "invokeNativeCode");

                var config = new WKWebViewConfiguration {
                    UserContentController = userController
                };
                var webView = new WKWebView(Frame, config);

                SetNativeControl(webView);
            }
            if (e.OldElement != null)
            {
                userController.RemoveAllUserScripts();
                userController.RemoveScriptMessageHandler("invokeNativeCode");
                var hybridWebView = e.OldElement as HybridWebView;
                hybridWebView.Cleanup();
            }
            if (e.NewElement != null)
            {
                string fileName = Path.Combine(NSBundle.MainBundle.BundlePath, string.Format("Content/{0}", Element.Uri));
                Control.LoadRequest(new NSUrlRequest(new NSUrl(fileName, false)));
                (e.NewElement as HybridWebView).NativeEvent += HybridWebViewRenderer_NativeEvent;
                //var fileContents = File.ReadAllText(fileName);
                //Control.LoadHtmlString(fileContents, new NSUrl(NSBundle.MainBundle.BundlePath + "/Content", true));
            }
        }
        /// <summary>
        /// ⽬目前不不⽤用此⽅方法实现js被调⽤用
        /// </summary>
        /// <param name="e"></param>
        protected override void OnElementChanged(ElementChangedEventArgs <HyBridWebView> e)
        {
            //给JS⽅方法重命名(多参数需要放在⼀一个字典⾥里里⾯面)
            const string rename1 = "function UserId(data){window.webkit.messageHandlers.UserId.postMessage(data);}";

            if (e.OldElement != null)
            {
                userController.RemoveAllUserScripts();
                userController.RemoveScriptMessageHandler("UserId");
            }
            if (e.NewElement != null)
            {
                if (Control == null)
                {
                    userController = new WKUserContentController();
                    userController.AddScriptMessageHandler(this, "UserId");
                    var config = new WKWebViewConfiguration {
                        UserContentController = userController
                    };
                    var webView = new WKWebView(Frame, config);
                    _webView = webView;
                    SetNativeControl(webView);
                }
                hyBridWebView = e.NewElement as HyBridWebView;
                UrlWebViewSource    source  = e.NewElement.Source as UrlWebViewSource;
                NSMutableUrlRequest request = new NSMutableUrlRequest(new NSUrl(source.Url));
                Control.LoadRequest(new NSUrlRequest(new NSUrl(source.Url)));
            }
        }
        public TrustlyWKWebView(string checkoutUrl, CGRect frame) : base(frame)
        {
            try
            {
                //Create a new content controller.
                var userContentController = new WKUserContentController();
                //Create configuration
                var configuration = new WKWebViewConfiguration();
                configuration.UserContentController = userContentController;
                configuration.Preferences.JavaScriptCanOpenWindowsAutomatically = true;

                //Crate a webview
                TrustlyView = new WKWebView(frame, configuration);
                TrustlyView.NavigationDelegate = this;
                TrustlyView.UIDelegate         = this;
                TrustlyView.NavigationDelegate = this;
                TrustlyView.UIDelegate         = this;

                //Add the trustly ScriptOpenURLScheme as a handler for this contentcontroller
                userContentController.AddScriptMessageHandler(new TrustlyWKScriptOpenURLScheme(TrustlyView), TrustlyWKScriptOpenURLScheme.NAME);

                var url = new NSUrl(checkoutUrl);

                TrustlyView.LoadRequest(new NSUrlRequest(url));
                TrustlyView.AllowsBackForwardNavigationGestures = true;

                AddSubview(TrustlyView);
                TrustlyView.TranslatesAutoresizingMaskIntoConstraints = false;
                TrustlyView.BottomAnchor.ConstraintEqualTo(TrustlyView.Superview.BottomAnchor, 0).Active     = true;
                TrustlyView.TopAnchor.ConstraintEqualTo(TrustlyView.Superview.TopAnchor, 0).Active           = true;
                TrustlyView.LeadingAnchor.ConstraintEqualTo(TrustlyView.Superview.LeadingAnchor, 0).Active   = true;
                TrustlyView.TrailingAnchor.ConstraintEqualTo(TrustlyView.Superview.TrailingAnchor, 0).Active = true;
            }
            catch { }
        }
Esempio n. 27
0
        public async void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
        {
            StartActivityIndicatorWithText("Download in progress..", new CoreGraphics.CGRect(82.5, 225, 200, 200));
            await Task.Delay(2000);

            StopActivityIndicator();
            var msg = message.Body.ToString();

            string[] urlArray = msg.Split(',');
            if (AppDelegate.filesDownloading != null)
            {
                AppDelegate.filesDownloading.RemoveAllObjects();
                AppDelegate.filesDownloaded.RemoveAllObjects();
            }
            AppDelegate.filesDownloading = new NSMutableArray();
            AppDelegate.filesDownloaded  = new NSMutableArray();

            foreach (string urlfromArray in urlArray)
            {
                string urlString = System.Web.HttpUtility.UrlDecode(urlfromArray.ToString());
                string fileType  = urlString.Substring(urlString.Length - 3);
                int    idx       = urlString.LastIndexOf('/');
                var    fileName  = urlString.Substring(idx + 1);
                AppDelegate.filesDownloading.Add(NSObject.FromObject(fileName));
                NSUrl downloadURL = NSUrl.FromString(urlfromArray);
                DownloadFiles(downloadURL);
            }
        }
        protected override void OnElementChanged(ElementChangedEventArgs <HybridWebView> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                _userController = new WKUserContentController();
                var script = new WKUserScript(new NSString(JSFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
                _userController.AddUserScript(script);
                _userController.AddScriptMessageHandler(this, "invokeAction");

                var config = new WKWebViewConfiguration {
                    UserContentController = _userController
                };
                var webView = new WKWebView(Frame, config);
                SetNativeControl(webView);
            }

            if (e.OldElement != null)
            {
                _userController.RemoveAllUserScripts();
                _userController.RemoveScriptMessageHandler("invokeAction");
                var hybridWebView = e.OldElement as HybridWebView;
                hybridWebView.Cleanup();
            }

            if (e.NewElement != null)
            {
                Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Uri)));
            }
        }
        public void AppDomainInitializer()
        {
            var userController = new WKUserContentController();

            userController.AddScriptMessageHandler(this, "myapp");

            var config = new WKWebViewConfiguration
            {
                UserContentController = userController
            };

            webview_real = new WKWebView(View.Frame, config);
            View.AddSubview(webview_real);

            #region load from file
            string htmlPath     = NSBundle.MainBundle.PathForResource("Alerts", "html");
            string htmlContents = File.ReadAllText(htmlPath);
            webview_real.LoadHtmlString(htmlContents, null);
            #endregion


            #region load from url sample
            //var url = "https://www.google.com.tw";
            //webview_real.LoadRequest(new NSUrlRequest(new NSUrl(url)));
            #endregion
        }
Esempio n. 30
0
        protected override void OnElementChanged(ElementChangedEventArgs <HybridWebPlatformView> e)
        {
            base.OnElementChanged(e);

            if (Control == null && e.NewElement != null)
            {
                userController = new WKUserContentController();

                var config = new WKWebViewConfiguration()
                {
                    UserContentController = userController
                };

                var script = new WKUserScript(new NSString(NativeFunction + HybridWebPlatformView.GetInitialJsScript(NativeFuncCall)), WKUserScriptInjectionTime.AtDocumentEnd, false);

                userController.AddUserScript(script);

                userController.AddScriptMessageHandler(this, "native");

                var webView = new WKWebView(Frame, config)
                {
                    NavigationDelegate = CreateNavidationalDelagate(), UIDelegate = new HybridWebPlatformUIDelegate()
                };

                webView.Opaque = false;

                webView.BackgroundColor = UIColor.Clear;

                SetNativeControl(webView);
            }

            e.NewElement.SetViewRenderer(this);
        }
        public override void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
        {
            SystemLogger.Log (SystemLogger.Module.PLATFORM, "# IPhoneWKScriptMessageHandler - DidReceiveScriptMessage");

            try {
                NSDictionary body = message.Body as NSDictionary;

                string requestUrl = null;
                string query = null;

                string serviceName = "undefined";
                string methodName = "undefined";
                Object service = null;

                if (body.ContainsKey (new NSString ("uri"))) {
                    requestUrl = (body ["uri"]).ToString ();

                    // get service path
                    if (requestUrl != null) {
                        if (requestUrl.StartsWith (IPhoneServiceLocator.APPVERSE_SERVICE_URI)) {
                            string commandParams = requestUrl.Substring (IPhoneServiceLocator.APPVERSE_SERVICE_URI.Length);
                            //SystemLogger.Log (SystemLogger.Module.PLATFORM, "# IPhoneWKScriptMessageHandler - commandParams: " + commandParams);
                            string[] commandParamsArray = commandParams.Split (new char[] { '/' });
                            serviceName = commandParamsArray [0];
                            methodName = commandParamsArray [1];
                            //SystemLogger.Log (SystemLogger.Module.PLATFORM, "# IPhoneWKScriptMessageHandler - serviceName: " + serviceName);
                            //SystemLogger.Log (SystemLogger.Module.PLATFORM, "# IPhoneWKScriptMessageHandler - methodName: " + methodName);
                            service = serviceLocator.GetService (serviceName);
                        }
                    }

                }

                if (body.ContainsKey (new NSString ("query"))) {
                    query = (body ["query"]).ToString ();
                    //SystemLogger.Log (SystemLogger.Module.PLATFORM, "# IPhoneWKScriptMessageHandler - query: " + query);
                }

                SystemLogger.Log (SystemLogger.Module.PLATFORM, "# IPhoneWKScriptMessageHandler - sending Async POST result for service: " + serviceName + ", and method: " + methodName);

                serviceURIHandler.ProcessAsyncPOSTResult (serviceInvocationManager, service, methodName, query);

            } catch (Exception ex) {
                SystemLogger.Log (SystemLogger.Module.PLATFORM, "# IPhoneWKScriptMessageHandler - exception handling WKScriptMessage. Exception message: " + ex.Message);
            }
        }
        public override void CustomizeWebView()
        {
            WKWebViewConfiguration config = new WKWebViewConfiguration ();

            // Adding Custom Message Handler
            WKUserContentController userContentController = new WKUserContentController ();
            WKScriptMessageHandler scriptMessageHandler = new IPhoneWKScriptMessageHandler ();
            userContentController.AddScriptMessageHandler (scriptMessageHandler, "service");
            config.UserContentController = userContentController;

            // UIScreen screen = UIScreen.MainScreen;
            // RectangleF viewFrame = new RectangleF (new PointF (0, 0), new SizeF (320, 480));
            this.webView = new WKWebView (this.View.Frame, config);
            //log ("************************* UnityUI_iOSViewController_WKWebView this.View.Frame.Height: " + this.View.Frame.Height);
            log ("UnityUI_iOSViewController_WKWebView removing bounces on WKWebView.ScrollView.");
            this.webView.ScrollView.Bounces = false;   // TESTING REMOVING BOUNCYNG

            this.View.AddSubview (this.webView);
        }