コード例 #1
0
        public override void ConnectionStateChanged(int state)
        {
            System.Diagnostics.Debug.WriteLine("ConnectionStateChanged: " + state.ToString());
            string stateString = string.Empty;

            switch (state)
            {
            case 0:
                stateString = "DISCONNECTED";
                break;

            case 1:
                stateString = "CONNECTING";
                break;

            case 2:
                stateString = "CONNECTED";
                break;

            default:
                break;
            }
            if (_webView != null)
            {
                UIApplication.SharedApplication.InvokeOnMainThread(delegate { _webView.EvaluateJavascript("writeInfo('info','LineaPro status: " + stateString + " " + DateTime.UtcNow.TimeOfDay.ToString() + "');"); });
            }
        }
コード例 #2
0
        private bool ShouldStartLoad(NSUrlRequest request, UIWebViewNavigationType navigationType)
        {
            if (request.Url.AbsoluteString.StartsWith("app://resize"))
            {
                try
                {
                    var size = WebView.EvaluateJavascript("size();");
                    if (size != null)
                    {
                        float.TryParse(size, out _height);
                    }

                    if (HeightChanged != null)
                    {
                        HeightChanged(_height);
                    }
                }
                catch
                {
                }

                return(false);
            }

            if (!request.Url.AbsoluteString.StartsWith("file://"))
            {
                if (UrlRequested != null)
                {
                    UrlRequested(request.Url.AbsoluteString);
                }
                return(false);
            }

            return(true);
        }
コード例 #3
0
 void CompassStart()
 {
     if (_locationManager != null)
     {
         _locationManager = new CLLocationManager();
         //_locationManager.Delegate = new CLLocationManagerDelegate();
         _locationManager.UpdatedHeading += delegate(object sender, CLHeadingUpdatedEventArgs e) {
             string javascript = string.Format("compass.onCompassSuccess({0:0.00})", _locationManager.Heading.MagneticHeading);
             _webView.EvaluateJavascript(javascript);
         };
         _locationManager.StartUpdatingHeading();
     }
 }
コード例 #4
0
 public override void ViewDidLoad()
 {
     base.ViewDidLoad();
     this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Cancel, (x, y) => this.DismissViewController(true, null));
     this.webview            = new UIWebView(this.View.Frame);
     webview.ShouldStartLoad = (webView, request, navType) => { return(true); };
     webview.LoadFinished   += (object sender, EventArgs e) => {
         var payload = webview.EvaluateJavascript("document.title");
         Console.WriteLine(payload);
         if (payload.Contains("Success payload="))
         {
             payload = Encoding.UTF8.GetString(Convert.FromBase64String(payload.Replace("Success payload=", String.Empty)));
             var rawToken = JsonConvert.DeserializeObject <Dictionary <string, string> >(payload);
             OnAuthenticationResponseArrived(new AuthenticationResponseEventArgs {
                 Success = true, TokenInfo = rawToken
             });
             this.InvokeOnMainThread(() => (UIApplication.SharedApplication.Delegate.Window.RootViewController.DismissViewController(true, null)));
         }
         else if (payload.Contains("Error message="))
         {
             OnAuthenticationResponseArrived(new AuthenticationResponseEventArgs {
                 Success = true, ErrorMessage = payload.Replace("Error message=", String.Empty)
             });
         }
     };
     this.View.AddSubview(webview);
     webview.LoadRequest(new NSUrlRequest(this.signInEndpoint));
 }
コード例 #5
0
        bool HandleShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
        {
            // If the URL is not our own custom scheme, just let the webView load the URL as usual
            var scheme = "hybrid:";

            if (request.Url.Scheme != scheme.Replace(":", ""))
            {
                return(true);
            }

            // This handler will treat everything between the protocol and "?"
            // as the method name.  The querystring has all of the parameters.
            var resources  = request.Url.ResourceSpecifier.Split('?');
            var method     = resources[0];
            var parameters = System.Web.HttpUtility.ParseQueryString(resources[1]);

            if (method == "UpdateLabel")
            {
                var textbox = parameters["textbox"];

                // Add some text to our string here so that we know something
                // happened on the native part of the round trip.
                var prepended = string.Format("C# says \"{0}\"", textbox);

                // Build some javascript using the C#-modified result
                var js = string.Format("SetLabelText('{0}');", prepended);

                webView.EvaluateJavascript(js);
            }

            return(false);
        }
コード例 #6
0
        void HandleLoadFinished(object sender, EventArgs e)
        {
            InvokeOnMainThread(() =>
            {
                this.activitySpinner.StopAnimating();
                this.View.UserInteractionEnabled = true;
            });
            var payload = webview.EvaluateJavascript("document.title");

            Console.WriteLine(payload);
            if (payload.Contains("Success payload="))
            {
                payload = Encoding.UTF8.GetString(Convert.FromBase64String(payload.Replace("Success payload=", String.Empty)));
                var rawToken = JsonConvert.DeserializeObject <Dictionary <string, string> > (payload);
                OnAuthenticationResponseArrived(new AuthenticationResponseEventArgs {
                    Success   = true,
                    TokenInfo = rawToken
                });

                this.InvokeOnMainThread(() => this.DismissViewController(true, null));
            }
            else
            if (payload.Contains("Error message="))
            {
                OnAuthenticationResponseArrived(new AuthenticationResponseEventArgs {
                    Success      = false,
                    ErrorMessage = payload.Replace("Error message=", String.Empty)
                });
            }
        }
コード例 #7
0
        public HtmlElement(string cellKey)
        {
            Key = new NSString(cellKey);

            _height = 10f;

            WebView                          = new UIWebView();
            WebView.Frame                    = new CGRect(0, 0, 320f, 44f);
            WebView.AutoresizingMask         = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
            WebView.ScrollView.ScrollEnabled = false;
            WebView.ScalesPageToFit          = true;
            WebView.ScrollView.Bounces       = false;
            WebView.ShouldStartLoad          = (w, r, n) => ShouldStartLoad(r, n);

            WebView.LoadFinished += (sender, e) =>
            {
                var f = WebView.Frame;
                f.Height      = _height = int.Parse(WebView.EvaluateJavascript("document.body.scrollHeight;"));
                WebView.Frame = f;

                if (HeightChanged != null)
                {
                    HeightChanged(_height);
                }
            };

            HeightChanged = (x) => Reload();
        }
コード例 #8
0
        public DeviceInfo()
        {
            UIWebView agentWebView = new UIWebView();

            UserAgent = agentWebView.EvaluateJavascript("navigator.userAgent");
            Display   = new Dimensions(Convert.ToInt32(UIScreen.MainScreen.Bounds.Size.Height), Convert.ToInt32(UIScreen.MainScreen.Bounds.Size.Width));
        }
コード例 #9
0
        public DeviceInfo()
        {
            //https://gist.github.com/crdeutsch/6707396
            UIWebView agentWebView = new UIWebView();

            UserAgent = agentWebView.EvaluateJavascript("navigator.userAgent");
        }
コード例 #10
0
 public TEditorViewController() : base()
 {
     _richTextEditor = new TEditor.Abstractions.TEditor();
     _richTextEditor.SetJavaScriptEvaluatingFunction((input) => {
         _webView.EvaluateJavascript(input);
     });
     _richTextEditor.SetJavaScriptEvaluatingWithResultFunction((input) => {
         return(Task.Run <string>(() => {
             string res = string.Empty;
             InvokeOnMainThread(() => {
                 res = _webView.EvaluateJavascript(input);
             });
             return res;
         }));
     });
 }
コード例 #11
0
        bool HandleShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
        {
            // If the URL is not our own custom scheme, just let the webView load the URL as usual
            const string scheme = "hybrid:";

            if (request.Url.Scheme != scheme.Replace (":", ""))
                return true;

            // This handler will treat everything between the protocol and "?"
            // as the method name.  The querystring has all of the parameters.
            var resources = request.Url.ResourceSpecifier.Split ('?');
            var method = resources [0];
            var parameters = System.Web.HttpUtility.ParseQueryString (resources [1]);

            if (method == "UpdateLabel") {
                var textbox = parameters ["textbox"];

                // Add some text to our string here so that we know something
                // happened on the native part of the round trip.
                var prepended = string.Format ("C# says: {0}", textbox);

                // Build some javascript using the C#-modified result
                var js = string.Format ("SetLabelText('{0}');", prepended);

                webView.EvaluateJavascript (js);
            }

            return false;
        }
コード例 #12
0
        public WebBrowserViewController(bool navigationToolbar, bool showPageAsTitle = false)
        {
            NavigationItem.BackBarButtonItem = new UIBarButtonItem {
                Title = ""
            };
            NavigationItem.LeftBarButtonItem = _closeButton;

            _web = new UIWebView {
                ScalesPageToFit = true
            };
            _web.ShouldStartLoad = (w, r, n) => true;

            _web.LoadStarted += (sender, e) => {
                NetworkActivityService.Instance.PushNetworkActive();
                _refreshButton.Enabled = false;
            };

            _web.LoadError += (sender, e) => {
                _refreshButton.Enabled = true;
            };

            _web.LoadFinished += (sender, e) => {
                NetworkActivityService.Instance.PopNetworkActive();
                _backButton.Enabled    = _web.CanGoBack;
                _forwardButton.Enabled = _web.CanGoForward;
                _refreshButton.Enabled = true;

                if (showPageAsTitle)
                {
                    Title = _web.EvaluateJavascript("document.title");
                }
            };

            if (navigationToolbar)
            {
                ToolbarItems = new [] {
                    _backButton,
                    new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace)
                    {
                        Width = 40f
                    },
                    _forwardButton,
                    new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
                    _refreshButton
                };
            }

            EdgesForExtendedLayout = UIRectEdge.None;

            this.WhenAnyValue(x => x.ViewModel.Uri)
            .SubscribeSafe(x => _web.LoadRequest(new NSUrlRequest(new NSUrl(x.AbsoluteUri))));

            OnActivation(d => {
                d(_backButton.GetClickedObservable().Subscribe(_ => _web.GoBack()));
                d(_forwardButton.GetClickedObservable().Subscribe(_ => _web.GoForward()));
                d(_refreshButton.GetClickedObservable().Subscribe(_ => _web.Reload()));
                d(_closeButton.GetClickedObservable().Subscribe(_ => DismissViewController(true, null)));
            });
        }
コード例 #13
0
 static string ConstructUserAgent()
 {
     using (var webView = new UIWebView())
     {
         var result = webView.EvaluateJavascript("navigator.userAgent");
         return(result);
     }
 }
コード例 #14
0
ファイル: WebViewExtensions.cs プロジェクト: Zebra/iFactr-iOS
 public static float GetDocumentHeight(this UIWebView webView)
 {
     try
     {
         return(Convert.ToSingle(webView.EvaluateJavascript(@"document.body.scrollHeight;")));
     }
     catch { return(54); }
 }
コード例 #15
0
        public DeviceInfo()
        {
            UIWebView agentWebView = new UIWebView();
            UserAgent = agentWebView.EvaluateJavascript("navigator.userAgent");
            Display = new Dimensions(Convert.ToInt32(UIScreen.MainScreen.Bounds.Size.Height), Convert.ToInt32(UIScreen.MainScreen.Bounds.Size.Width));

            GoogleAnalyticsFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), GoogleAnalyticsFolder);
        }
コード例 #16
0
ファイル: WebViewExtensions.cs プロジェクト: Zebra/iFactr-iOS
        public static void AutoplayVideo(this UIWebView webView)
        {
            string script = @"  var elements = document.getElementsByTagName('video');
								if(elements.length > 0){
									elements[0].play();
								}"                                ;

            webView.EvaluateJavascript(script);
        }
コード例 #17
0
        public static void FireEvent(this UIWebView source, string EventName, Object Data)
        {
            // call javascript event hanlder code
            string json = SimpleJson.SerializeObject(Data);

            source.BeginInvokeOnMainThread(delegate {
                source.EvaluateJavascript(string.Format("Mt.App._dispatchEvent('{0}', {1});", EventName, json));
            });
        }
コード例 #18
0
ファイル: WebViewExtensions.cs プロジェクト: Zebra/iFactr-iOS
        public static void ClearVideoContent(this UIWebView webView)
        {
            string script = @"
					        var elements = document.getElementsByTagName('video');
					        for(var i=0; i< elements.length; i++){
					            elements[i].pause();
					        }"                            ;

            webView.EvaluateJavascript(script);
        }
コード例 #19
0
ファイル: AuthViewController.cs プロジェクト: dfsklar/Mobile
        async void WebView_LoadFinished(object sender, EventArgs e)
        {
            var url   = webView.EvaluateJavascript("window.location.href");
            var match = Provider == "Vimeo" ? Constants.VimeoRedirectURL : Constants.YouTubeRedirectURL;

            if (!url.StartsWith(match))
            {
                return;
            }
            var split = url.Split('=');

            if (split.Length == 0)
            {
                return;
            }
            var code = split [split.Length - 1];

            foreach (var view in View.Subviews)
            {
                view.RemoveFromSuperview();
            }

            var text = new UILabel(new CoreGraphics.CGRect(0, 0, 400, 90));

            text.Text          = "Loading...";
            text.TextAlignment = UITextAlignment.Center;
            text.Center        = View.Center;
            text.TextColor     = UIColor.Black;
            View.Add(text);

            InvokeInBackground(delegate {
                if (Provider == "Vimeo")
                {
                    var hook = VimeoHook.Authorize(
                        authCode: code,
                        clientId: Constants.VimeoAPIKey,
                        secret: Constants.VimeoAPISecret,
                        redirect: Constants.VimeoRedirectURL);
                    InvokeOnMainThread(delegate {
                        text.Text = string.Format("Logged in as {0}!", hook.User ["name"].Value);
                    });
                }
                else if (Provider == "YouTube")
                {
                    var hook = YouTubeHook.Authorize(
                        authCode: code,
                        clientId: Constants.YouTubeAPIKey,
                        secret: Constants.YouTubeAPISecret,
                        redirect: Constants.YouTubeRedirectURL);
                    InvokeOnMainThread(delegate {
                        text.Text = string.Format("Logged in as {0}!", hook.DisplayName);
                    });
                }
            });
        }
コード例 #20
0
        public void AppendPageContent(UIWebView webView, string content, string direction)
        {
            if (content != null)
            {
                content = ContentFormatUtil.Format(content);

                content = content.Replace("\"", "##");
                content = Regex.Replace(content, @"[\r|\n]", "");
                webView.EvaluateJavascript("appendPageContent(\"" + content + "\", \"" + direction + "\");");
            }
        }
コード例 #21
0
        public WebView(bool navigationToolbar, bool showPageAsTitle = false)
        {
            NavigationItem.BackBarButtonItem = new UIBarButtonItem()
            {
                Title = ""
            };
            Web = new UIWebView {
                ScalesPageToFit = true
            };
            Web.LoadFinished   += OnLoadFinished;
            Web.LoadStarted    += OnLoadStarted;
            Web.LoadError      += OnLoadError;
            Web.ShouldStartLoad = (w, r, n) => ShouldStartLoad(r, n);

            if (showPageAsTitle)
            {
                Web.LoadFinished += (sender, e) =>
                {
                    Title = Web.EvaluateJavascript("document.title");
                };
            }

            _navigationToolbar = navigationToolbar;

            if (_navigationToolbar)
            {
                ToolbarItems = new [] {
                    (BackButton = new UIBarButtonItem(Theme.CurrentTheme.WebBackButton, UIBarButtonItemStyle.Plain, (s, e) => GoBack())
                    {
                        Enabled = false
                    }),
                    new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace)
                    {
                        Width = 40f
                    },
                    (ForwardButton = new UIBarButtonItem(Theme.CurrentTheme.WebFowardButton, UIBarButtonItemStyle.Plain, (s, e) => GoForward())
                    {
                        Enabled = false
                    }),
                    new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
                    (RefreshButton = new UIBarButtonItem(UIBarButtonSystemItem.Refresh, (s, e) => Refresh()))
                };

                BackButton.TintColor    = Theme.CurrentTheme.WebButtonTint;
                ForwardButton.TintColor = Theme.CurrentTheme.WebButtonTint;
                RefreshButton.TintColor = Theme.CurrentTheme.WebButtonTint;

                BackButton.Enabled    = false;
                ForwardButton.Enabled = false;
                RefreshButton.Enabled = false;
            }

            EdgesForExtendedLayout = UIRectEdge.None;
        }
コード例 #22
0
		//
		// This method is invoked when the application has loaded and is ready to run. In this 
		// method you should instantiate the window, load the UI into it and then make the window
		// visible.
		//
		// You have 17 seconds to return from this method, or iOS will terminate your application.
		//
		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			JsBridge.EnableJsBridge();

			window = new UIWindow (UIScreen.MainScreen.Bounds);

			// get useragent
			UIWebView agentWebView = new UIWebView ();
			var userAgent = agentWebView.EvaluateJavascript ("navigator.userAgent");
			agentWebView = null;
			userAgent += " XamarinBarcodeSampleApp";

			// set default useragent
			NSDictionary dictionary = NSDictionary.FromObjectAndKey(NSObject.FromObject(userAgent), NSObject.FromObject("UserAgent"));
			NSUserDefaults.StandardUserDefaults.RegisterDefaults(dictionary);

			viewController = new Xamarin_iOS_BarcodeSampleViewController ();
			window.RootViewController = viewController;
			window.MakeKeyAndVisible ();

			viewController.MainWebView.LoadRequest(new NSUrlRequest(new NSUrl("http://xamarinbarcodesample.apphb.com/")));

			// listen for the event triggered by the browser.
			viewController.MainWebView.AddEventListener( "scanBarcode", delegate(FireEventData arg) {

				// show a native action sheet
				BeginInvokeOnMainThread (delegate { 
					//NOTE: On Android you MUST pass a Context into the Constructor!
					var scanningOptions = new ZXing.Mobile.MobileBarcodeScanningOptions();
					scanningOptions.PossibleFormats = new List<ZXing.BarcodeFormat>() { 
						ZXing.BarcodeFormat.All_1D
					};
					scanningOptions.TryInverted = true;
					scanningOptions.TryHarder = true;
					scanningOptions.AutoRotate = false;
					var scanner = new ZXing.Mobile.MobileBarcodeScanner();
					scanner.TopText = "Hold camera up to barcode to scan";
					scanner.BottomText = "Barcode will automatically scan";
					scanner.Scan(scanningOptions).ContinueWith(t => {   
						if (t.Result != null) {
							//Console.WriteLine("Scanned Barcode: " + t.Result.Text);

							// pass barcode back to browser.
							viewController.MainWebView.FireEvent( "scanComplete", new {
								code = t.Result.Text
							});
						}
					});
				});

			});
			
			return true;
		}
コード例 #23
0
 public void Init()
 {
     try
     {
         using (var agentWebView = new UIWebView())
             userAgent = agentWebView.EvaluateJavascript("navigator.userAgent");
     }
     catch
     {
     }
 }
コード例 #24
0
 public override void LoadingFinished(UIWebView webView)
 {
     try {
         var t = webView.EvaluateJavascript("document.title");
         if (t.Length > 0)
         {
             _c.Title = t;
         }
     } catch (Exception error) {
         Log.Error(error);
     }
 }
コード例 #25
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            View.BackgroundColor = UIColor.White;

            webView = new UIWebView(View.Bounds);
            View.AddSubview(webView);
            webView.ShouldStartLoad = (webView, request, navType) =>
            {
//                System.Console.WriteLine("###" + request.Url.AbsoluteString);
                if (request.Url.AbsoluteString == "myapp://scan")
                {
                    var options = new ZXing.Mobile.MobileBarcodeScanningOptions
                    {
                        PossibleFormats = new List <ZXing.BarcodeFormat>()
                        {
                            ZXing.BarcodeFormat.EAN_8, ZXing.BarcodeFormat.EAN_13, ZXing.BarcodeFormat.CODE_128
                        }
                    };

                    var scanner = new ZXing.Mobile.MobileBarcodeScanner
                    {
                        //                    scanner.ScanContinuously(HandleScanResult);
                        TopText    = "Поднесите камеру к штрих-коду для сканирования",
                        BottomText = "Штрих-код будет автоматически отсканирован"
                    };
                    scanner.Scan(options).ContinueWith(t => {
                        var result = t.Result;

                        var format = result?.BarcodeFormat.ToString() ?? string.Empty;
                        var value  = result?.Text ?? string.Empty;

                        BeginInvokeOnMainThread(() => {
                            if (value != null && !string.IsNullOrEmpty(value))
                            {
                                webView.EvaluateJavascript("location.href = '/search?q=" + value + "';");
                            }
//                            var av = UIAlertController.Create("Barcode Result", format + "|" + value, UIAlertControllerStyle.Alert);
//                            av.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, null));
//                            PresentViewController(av, true, null);
                        });
                    });
                }
                return(true);
            };
            var url = "https://mobile.kcentr.ru";

            webView.LoadRequest(new NSUrlRequest(new NSUrl(url)));

            // if this is false, page will be 'zoomed in' to normal size
            webView.ScalesPageToFit = false;
        }
コード例 #26
0
        protected void UpdateTitle()
        {
            string title = _webView.EvaluateJavascript("document.title");

            if (!string.IsNullOrEmpty(title))
            {
                Title = title;
            }
            else
            {
                Title = _webView.Request.Url.AbsoluteString;
            }
        }
コード例 #27
0
        public WebBrowserViewController(bool navigationToolbar, bool showPageAsTitle = false)
        {
            NavigationItem.BackBarButtonItem = new UIBarButtonItem {
                Title = ""
            };
            NavigationItem.LeftBarButtonItem = new UIBarButtonItem(Images.Cancel, UIBarButtonItemStyle.Plain, (s, e) => DismissViewController(true, null));

            Web = new UIWebView {
                ScalesPageToFit = true
            };
            Web.LoadFinished   += OnLoadFinished;
            Web.LoadStarted    += OnLoadStarted;
            Web.LoadError      += OnLoadError;
            Web.ShouldStartLoad = (w, r, n) => ShouldStartLoad(r, n);

            if (showPageAsTitle)
            {
                Web.LoadFinished += (sender, e) =>
                {
                    Title = Web.EvaluateJavascript("document.title");
                };
            }

            _navigationToolbar = navigationToolbar;

            if (_navigationToolbar)
            {
                ToolbarItems = new [] {
                    (BackButton = new UIBarButtonItem(Images.BackChevron, UIBarButtonItemStyle.Plain, (s, e) => GoBack())
                    {
                        Enabled = false
                    }),
                    new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace)
                    {
                        Width = 40f
                    },
                    (ForwardButton = new UIBarButtonItem(Images.ForwardChevron, UIBarButtonItemStyle.Plain, (s, e) => GoForward())
                    {
                        Enabled = false
                    }),
                    new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
                    (RefreshButton = new UIBarButtonItem(UIBarButtonSystemItem.Refresh, (s, e) => Refresh()))
                };

                BackButton.Enabled    = false;
                ForwardButton.Enabled = false;
                RefreshButton.Enabled = false;
            }

            EdgesForExtendedLayout = UIRectEdge.None;
        }
コード例 #28
0
        public void CheckHeight()
        {
            var f = WebView.Frame;

            f.Height      = 1;
            WebView.Frame = f;
            f.Height      = _height = int.Parse(WebView.EvaluateJavascript("document.body.scrollHeight;"));
            WebView.Frame = f;

            if (HeightChanged != null)
            {
                HeightChanged(_height);
            }
        }
コード例 #29
0
ファイル: WebViewExtensions.cs プロジェクト: Zebra/iFactr-iOS
        public static string GetElementRect(this UIWebView webView, string element)
        {
            string script = @"  var target = {0};
                                var x = 0, y = 0;
                                for (var n = target; n && n.nodeType == 1; n = n.offsetParent) {
                                  x += n.offsetLeft;
                                  y += n.offsetTop;
                                }
                                x + ',' + y + ',' + target.offsetWidth + ',' + target.offsetHeight;";

            String.Format(script, element);
            string result = webView.EvaluateJavascript(script);

            return(result);
        }
コード例 #30
0
		public override void LoadingFinished(UIWebView webView)
		{
			if (webView.Request.Url.ToString().Equals(redirectUrl))
			{
				if (Listener != null)
				{
					Listener.OnPageStarted();
				}
				// iOS adds default HTML when it encounters JSON content.
				var content = webView.EvaluateJavascript("document.getElementsByTagName('pre')[0].innerHTML");
				var json = JObject.Parse(content);

				handler.Invoke(this, new CardVerificationResult { md = (string)json["MD"], paRes = (string)json["PaRes"] });
			}
		}
コード例 #31
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var webView = new UIWebView(GetFrameWithVerticalMargin(20));

            LoadMapUrl(webView);

            Add(webView);

            webView.LoadFinished += (sender, e) =>
            {
                webView.EvaluateJavascript("displayGeocoordinate('New York');");
            };
        }
コード例 #32
0
ファイル: AppDelegate.cs プロジェクト: XamarinGuru/LiveTiles
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Override point for customization after application launch.
            // If not required for your application you can safely delete this method

            // Customize user agent string to include app name
            UIWebView agentWebView = new UIWebView();
            var       userAgent    = agentWebView.EvaluateJavascript("navigator.userAgent");

            userAgent = "LiveTilesMX/1.0 " + userAgent;
            NSDictionary dictionary = NSDictionary.FromObjectAndKey(NSObject.FromObject(userAgent), NSObject.FromObject("UserAgent"));

            NSUserDefaults.StandardUserDefaults.RegisterDefaults(dictionary);

            return(true);
        }
コード例 #33
0
        private void loadFinished(object sender, EventArgs e)
        {
            var   offsetHeight = webView.EvaluateJavascript("document.body.offsetHeight");
            float height       = 0;

            if (float.TryParse(offsetHeight, out height))
            {
                this.webView.Frame = new CoreGraphics.CGRect(0,
                                                             0,
                                                             this.webView.Frame.Width,
                                                             height);

                if (command != null)
                {
                    command.Execute(height);
                }
            }
        }
コード例 #34
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

            View.BackgroundColor = UIColor.White;

            webView = new UIWebView((CGRect)View.Bounds);
		    webView.ShouldStartLoad = (wView, request, navType) =>
		    {
		        if (request == null)
		        {
		            return true;
		        }

		        string requestUrl = request.Url.ToString().ToLower();
                if (requestUrl.StartsWith(callback.ToLower()))
                {
                    callbackMethod(new AuthorizationResult(AuthorizationStatus.Success, request.Url.ToString()));
                    this.DismissViewController(true, null);
                    return false;
                }

                return true;
		    };

		    webView.LoadFinished += delegate
		    {
                // If the title is too long, iOS automatically truncates it and adds ...
                this.Title = webView.EvaluateJavascript(@"document.title") ?? "Sign in";
		    };

			View.AddSubview(webView);

            this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Cancel, this.CancelAuthentication);

			webView.LoadRequest (new NSUrlRequest (new NSUrl (this.url)));
			
			// if this is false, page will be 'zoomed in' to normal size
			//webView.ScalesPageToFit = true;
		}
コード例 #35
0
ファイル: WebView.cs プロジェクト: rcaratchuk/CodeFramework
        public WebView(bool navigationToolbar, bool showPageAsTitle = false)
        {
            NavigationItem.BackBarButtonItem = new UIBarButtonItem() { Title = "" };
            Web = new UIWebView {ScalesPageToFit = true};
            Web.LoadFinished += OnLoadFinished;
            Web.LoadStarted += OnLoadStarted;
            Web.LoadError += OnLoadError;
            Web.ShouldStartLoad = (w, r, n) => ShouldStartLoad(r, n);

            if (showPageAsTitle)
            {
                Web.LoadFinished += (sender, e) =>
                {
                    Title = Web.EvaluateJavascript("document.title");
                };
            }

            _navigationToolbar = navigationToolbar;

            if (_navigationToolbar)
            {
                ToolbarItems = new [] {
                    (BackButton = new UIBarButtonItem(Theme.CurrentTheme.WebBackButton, UIBarButtonItemStyle.Plain, (s, e) => GoBack()) { Enabled = false }),
                    new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace) { Width = 40f },
                    (ForwardButton = new UIBarButtonItem(Theme.CurrentTheme.WebFowardButton, UIBarButtonItemStyle.Plain, (s, e) => GoForward()) { Enabled = false }),
                    new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
                    (RefreshButton = new UIBarButtonItem(UIBarButtonSystemItem.Refresh, (s, e) => Refresh()))
                };

                BackButton.TintColor = Theme.CurrentTheme.WebButtonTint;
                ForwardButton.TintColor = Theme.CurrentTheme.WebButtonTint;
                RefreshButton.TintColor = Theme.CurrentTheme.WebButtonTint;

                BackButton.Enabled = false;
                ForwardButton.Enabled = false;
                RefreshButton.Enabled = false;
            }

            EdgesForExtendedLayout = UIRectEdge.None;
        }
コード例 #36
0
ファイル: WebViewRow.cs プロジェクト: jivkopetiov/StackApp
            public InnerCell(string reuseIdentifier, UITableView tableView)
                : base(UITableViewCellStyle.Default, reuseIdentifier)
            {
                _tableView = tableView;
                _webView = new UIWebView();
                _webView.ScrollView.Bounces = false;

                _webView.LoadFinished += delegate {
                    Console.WriteLine ("load finished");
                    string jsResult = _webView.EvaluateJavascript("document.body.scrollHeight;");

                    height = int.Parse(jsResult);

                    _tableView.ReloadData();
                };

                _webView.LoadError += delegate {
                    Console.WriteLine ("load error");
                };

                Add(_webView);
            }
コード例 #37
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Cancel, (x,y) => this.DismissViewController(true,null));
			this.webview = new UIWebView (this.View.Frame);
			webview.ShouldStartLoad = (webView, request, navType) => {return true;};
			webview.LoadFinished+= (object sender, EventArgs e) => {
				var payload = webview.EvaluateJavascript("document.title");
				Console.WriteLine(payload);
				if (payload.Contains ("Success payload="))
				{
					payload = Encoding.UTF8.GetString(Convert.FromBase64String( payload.Replace("Success payload=", String.Empty)));
					var rawToken = JsonConvert.DeserializeObject<Dictionary<string,string>>(payload);
					OnAuthenticationResponseArrived (new AuthenticationResponseEventArgs { Success = true, TokenInfo = rawToken });
					this.InvokeOnMainThread( ()=> (UIApplication.SharedApplication.Delegate.Window.RootViewController.DismissViewController(true, null))) ;
				}
				else if (payload.Contains ("Error message=")) {
					OnAuthenticationResponseArrived (new AuthenticationResponseEventArgs { Success = true, ErrorMessage = payload.Replace("Error message=", String.Empty) });
				}
			};
			this.View.AddSubview (webview);
			webview.LoadRequest (new NSUrlRequest (this.signInEndpoint));
		}
コード例 #38
0
        public override void ViewDidLoad()
        {
            //base.ViewDidLoad();

            var webFrame = new RectangleF (0, 0, this.View.Frame.Width, this.View.Frame.Height - 44);

            webView = new UIWebView (webFrame) {
                BackgroundColor = UIColor.White,
                ScalesPageToFit = true,
                AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
            };

            webView.LoadStarted += delegate {
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
            };
            webView.LoadFinished += delegate {
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
                webView.EvaluateJavascript (script ());
            };

            this.View.AddSubview(webView);

            webView.LoadRequest(NSUrlRequest.FromUrl(new NSUrl(page.AbsoluteUri)));
        }
コード例 #39
0
ファイル: BrowserController.cs プロジェクト: jorik041/odata
 public override void LoadingFinished(UIWebView webView)
 {
     try {
         var t = webView.EvaluateJavascript ("document.title");
         if (t.Length > 0) {
             _c.Title = t;
         }
     } catch (Exception error) {
         Log.Error (error);
     }
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            View.BackgroundColor = UIColor.White;

            _webView = new UIWebView((CGRect) View.Bounds);
            _webView.ShouldStartLoad = (wView, request, navType) =>
            {
                if (request == null)
                {
                    return true;
                }

                string requestUrlString = request.Url.ToString();
                
                if (requestUrlString.StartsWith(BrokerConstants.BrowserExtPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    DispatchQueue.MainQueue.DispatchAsync(() => CancelAuthentication(null, null));
                    requestUrlString = requestUrlString.Replace(BrokerConstants.BrowserExtPrefix, "https://");
                    DispatchQueue.MainQueue.DispatchAsync(
                        () => UIApplication.SharedApplication.OpenUrl(new NSUrl(requestUrlString)));
                    this.DismissViewController(true, null);
                    return false;
                }

                if (requestUrlString.ToLower(CultureInfo.InvariantCulture).StartsWith(_callback.ToLower(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase) || requestUrlString.StartsWith(BrokerConstants.BrowserExtInstallPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    callbackMethod(new AuthorizationResult(AuthorizationStatus.Success, request.Url.ToString()));
                    this.DismissViewController(true, null);
                    return false;
                }

                if (requestUrlString.StartsWith(BrokerConstants.DeviceAuthChallengeRedirect, StringComparison.CurrentCultureIgnoreCase))
                {
                    Uri uri = new Uri(requestUrlString);
                    string query = uri.Query;
                    if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase))
                    {
                        query = query.Substring(1);
                    }

                    Dictionary<string, string> keyPair = EncodingHelper.ParseKeyValueList(query, '&', true, false, null);
                    string responseHeader = PlatformPlugin.DeviceAuthHelper.CreateDeviceAuthChallengeResponse(keyPair).Result;
                    
                    NSMutableUrlRequest newRequest = (NSMutableUrlRequest)request.MutableCopy();
                    newRequest.Url = new NSUrl(keyPair["SubmitUrl"]);
                    newRequest[BrokerConstants.ChallengeResponseHeader] = responseHeader;
                    wView.LoadRequest(newRequest);
                    return false;
                }
                
                if (!request.Url.AbsoluteString.Equals("about:blank", StringComparison.CurrentCultureIgnoreCase) && !request.Url.Scheme.Equals("https", StringComparison.CurrentCultureIgnoreCase))
                {
                    AuthorizationResult result = new AuthorizationResult(AuthorizationStatus.ErrorHttp);
                    result.Error = MsalError.NonHttpsRedirectNotSupported;
                    result.ErrorDescription = MsalErrorMessage.NonHttpsRedirectNotSupported;
                    callbackMethod(result);
                    this.DismissViewController(true, null);
                    return false;
                }


                return true;
            };

            _webView.LoadFinished += delegate
            {
                // If the title is too long, iOS automatically truncates it and adds ...
                this.Title = _webView.EvaluateJavascript(@"document.title") ?? "Sign in";
            };

            View.AddSubview(_webView);

            this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Cancel,
                this.CancelAuthentication);

            NSUrlRequest startRequest = new NSUrlRequest(new NSUrl(this._url));
            _webView.LoadRequest(startRequest);

            // if this is false, page will be 'zoomed in' to normal size
            //webView.ScalesPageToFit = true;
        }