示例#1
0
        private void OpenPopupInIframe(IWebBrowser browserControl, string url)
        {
            StringBuilder script = new StringBuilder();

            //if game
            foreach (var GameItem in WebPlaceSettings.GameUrlList)
            {
                if (url.Contains(GameItem))
                {
                    script.Append(string.Format("$(\".iframeGame\").prop(\"src\", \"{0}\");", url));
                    script.Append("openFrameGame();");
                    browserControl.ExecuteScriptAsync(script.ToString());
                    return;
                }
            }
            //if score
            foreach (var ScoreItem in WebPlaceSettings.ScoreUrlList)
            {
                if (url.Contains(ScoreItem))
                {
                    script.Append($"ShowRightPanel(\"{url}\");");
                    browserControl.ExecuteScriptAsync(script.ToString());
                    return;
                }
            }
        }
示例#2
0
        private static async void RunScriptsDefault(IWebBrowser browser)
        {
            browser.ExecuteScriptAsync("map = L.map('map');");
            browser.ExecuteScriptAsync("map.setView([51.505, -0.09], 13);");
            var url = @"https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw";

            browser.ExecuteScriptAsync($"tileLayer = L.tileLayer('{url}', {"{id: 'mapbox.streets'}"})");
            browser.ExecuteScriptAsync($"tileLayer.addTo(map);");
        }
        public static Task<IList<string>> EnsureObjectBoundAsync(this IWebBrowser browser, params string[] names)
        {
            var objBoundTasks = new TaskCompletionSource<IList<string>>();

            EventHandler<JavascriptBindingMultipleCompleteEventArgs> handler = null;
            handler = (sender, args) =>
            {
                //Remove handler
                browser.JavascriptObjectRepository.ObjectsBoundInJavascript -= handler;

                var allObjectsBound = names.ToList().SequenceEqual(args.ObjectNames);
                if (allObjectsBound)
                {
                    objBoundTasks.SetResult(args.ObjectNames);
                }
                else
                {
                    objBoundTasks.SetException(new Exception("Not all objects were bound successfully, bound objects were " + string.Join(",", args.ObjectNames)));
                }
            };

            browser.JavascriptObjectRepository.ObjectsBoundInJavascript += handler;

            var bindCommand = "(function() { CefSharp.BindObjectAsync({ NotifyIfAlreadyBound: true, IgnoreCache: false }, '" + string.Join("', '", names) + "'); })();";

            browser.ExecuteScriptAsync(bindCommand);

            return objBoundTasks.Task;
        }
示例#4
0
        async public void InitAjaxHandlers(IWebBrowser wb = null)
        {
            JavascriptResponse resp;

            if (wb == null)
            {
                resp = await m_Browser.EvaluateScriptAsync(JSRes.AJAX);
            }
            else
            {
                resp = await wb.EvaluateScriptAsync(JSRes.AJAX);
            }

            if (!resp.Success)
            {
                log.Error(resp.Message);
            }
            else
            {
                if (wb == null)
                {
                    m_Browser.ExecuteScriptAsync("InitAjaxHandlers", "");
                }
                else
                {
                    wb.ExecuteScriptAsync("InitAjaxHandlers", "");
                }
            }
        }
示例#5
0
        public void SendMessageToBrowser()
        {
            // message text ist bound to property
            if (String.IsNullOrEmpty(MessageText))
            {
                return;
            }

            _browser.ExecuteScriptAsync("window.applicationInterface.addMessage", MessageText);
        }
示例#6
0
        /// <summary>
        /// Execute Javascript code in the context of this WebBrowser. This extension method uses the LoadingStateChanged event.
        /// As the method name implies, the script will be executed asynchronously, and the method therefore returns before the
        /// script has actually been executed.
        /// </summary>
        /// <param name="webBrowser">The ChromiumWebBrowser instance this method extends</param>
        /// <param name="script">The Javascript code that should be executed.</param>
        /// <param name="oneTime">The script will only be executed on first page load, subsiquent page loads will be ignored</param>
        /// <remarks>Best effort is made to make sure the script is executed, there are likely a few edge cases where the script
        /// won't be executed, if you suspect your script isn't being executed, then try executing in the LoadingStateChanged
        /// event handler to confirm that it does indeed get executed.</remarks>
        public static void ExecuteScriptAsyncWhenPageLoaded(this IWebBrowser webBrowser, string script, bool oneTime = true)
        {
            var useLoadingStateChangedEventHandler = webBrowser.IsBrowserInitialized == false || oneTime == false;

            //Browser has been initialized, we check if there is a valid document and we're not loading
            if (webBrowser.IsBrowserInitialized)
            {
                //CefBrowser wrapper
                var browser = webBrowser.GetBrowser();
                if (browser.HasDocument && browser.IsLoading == false)
                {
                    webBrowser.ExecuteScriptAsync(script);
                }
                else
                {
                    useLoadingStateChangedEventHandler = true;
                }
            }

            //If the browser hasn't been initialized we can just wire up the LoadingStateChanged event
            //If the script has already been executed and oneTime is false will be hooked up next page load.
            if (useLoadingStateChangedEventHandler)
            {
                EventHandler <LoadingStateChangedEventArgs> handler = null;

                handler = (sender, args) =>
                {
                    //Wait for while page to finish loading not just the first frame
                    if (!args.IsLoading)
                    {
                        if (oneTime)
                        {
                            webBrowser.LoadingStateChanged -= handler;
                        }

                        webBrowser.ExecuteScriptAsync(script);
                    }
                };

                webBrowser.LoadingStateChanged += handler;
            }
        }
示例#7
0
 bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
 {
     if ((int)commandId == ShowDevTools)
     {
         browser.ShowDevTools();
     }
     if ((int)commandId == Close)
     {
         browserControl.ExecuteScriptAsync("cefsharp.CloseAPP();");
         //var frm = (Globals.GetInstance()["MainForm"] as Form);
         //frm.Invoke(new Action(() =>
         //{
         //    frm.Close();
         //}));
     }
     if ((int)commandId == Lock)
     {
         browserControl.ExecuteScriptAsync("cefsharp.Lock();");
     }
     return(false);//true表示拦截,默认false
 }
示例#8
0
 public bool OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
 {
     if (request.Url == KancolleUtils.KanColleUrl)
     {
         if (response.ResponseHeaders["Content-Length"] != null)
         {
             responseFilter.ContentLength = int.Parse(response.ResponseHeaders["Content-Length"]);
         }
     }
     else if (request.Url.StartsWith(KancolleUtils.KanColleFrameSrcPrefix))
     {//过滤掉多余的页面信息(貌似使用filter会出问题,使得岛风GO无法识别)
         gameFrame = frame;
         var script = "document.body.style.margin='0px';";
         browserControl.ExecuteScriptAsync(script);
         gameFrameFilter.ContentLength = int.Parse(response.ResponseHeaders["Content-Length"]);
     }
     else if (request.Url.Contains(KancolleUtils.KanColleAPIKeyword)) //(request.Url.StartsWith(KancolleCommon.DMMUrls.KanColleAPIUrl))
     {                                                                //获取api post
         RequestInfo requestInfo = new RequestInfo();
         requestInfo.RequestUrl = request.Url;
         foreach (var postData in request.PostData.Elements)
         {
             foreach (var kv in getParams(postData.GetBody()))
             {
                 requestInfo.Data.Add(kv.Key, kv.Value);
                 requestInfo.DataString += postData.GetBody() + " ";
             }
         }
         apiResponseFilter.InitFilter();
         apiResponseFilter.CurrentRequest = requestInfo;
         apiResponseFilter.ContentLength  = response.ResponseHeaders.Count == 0 ? 0 : int.Parse(response.ResponseHeaders["Content-Length"]);
     }
     else if (request.Url.StartsWith(KancolleUtils.KanColleSwfUrl))
     {
         RequestInfo requestInfo = new RequestInfo();
         string      requestUrl  = request.Url;
         int         pindex      = requestUrl.IndexOf("?");
         if (pindex > 0)
         {
             requestInfo.RequestUrl = requestUrl.Substring(0, pindex);
             requestInfo.DataString = requestUrl.Substring(pindex + 1);
             requestInfo.Data       = getParams(requestInfo.DataString);
         }
         else
         {
             requestInfo.RequestUrl = request.Url;
         }
         OnSwfResponseReceived?.Invoke(requestInfo, null);
     }
     return(false);
 }
示例#9
0
        private void OpenPopupInIframe2(IWebBrowser browserControl, string Url)
        {
            StringBuilder script = new StringBuilder();

            //script.Append(string.Format("alert('{0}');", Url));
            //script.Append(" $(\"#ButtonGame\").show();");
            //script.Append("$(\"#ButtonGame\").css(\"visibility\", \"visible\");");
            script.Append(string.Format("$(\"#SiteGame\").prop(\"src\", \"{0}\");", Url));
            script.Append("$(\"iframe\").hide();");
            script.Append("$(\"#GameDiv\").show();");
            script.Append("$(\"#GameDiv\").css(\"visibility\", \"visible\");");
            script.Append("$(\"#SiteGame\").show();");
            script.Append("$(\"#SiteGame\").css(\"visibility\", \"visible\");");
            script.Append("$(\"#mySidenav\").hide();");
            browserControl.ExecuteScriptAsync(script.ToString());
        }
示例#10
0
        /// <summary>
        /// Execute some Javascript code in the context of this WebBrowser. As the method name implies, the script will be
        /// executed asynchronously, and the method therefore returns before the script has actually been executed.
        /// This simple helper extension will encapsulate params in single quotes (unless int, uint, etc)
        /// </summary>
        /// <param name="browser">The ChromiumWebBrowser instance this method extends</param>
        /// <param name="methodName">The javascript method name to execute</param>
        /// <param name="args">the arguments to be passed as params to the method</param>
        public static void ExecuteScriptAsync(this IWebBrowser browser, string methodName, params object[] args)
        {
            var stringBuilder = new StringBuilder();

            stringBuilder.Append(methodName);
            stringBuilder.Append("(");

            if (args.Length > 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    var obj = args[i];
                    if (obj == null)
                    {
                        stringBuilder.Append("null");
                    }
                    else
                    {
                        var encapsulateInSingleQuotes = !numberTypes.Contains(obj.GetType());
                        if (encapsulateInSingleQuotes)
                        {
                            stringBuilder.Append("'");
                        }

                        stringBuilder.Append(args[i].ToString());

                        if (encapsulateInSingleQuotes)
                        {
                            stringBuilder.Append("'");
                        }
                    }

                    stringBuilder.Append(", ");
                }

                //Remove the trailing comma
                stringBuilder.Remove(stringBuilder.Length - 2, 2);
            }

            stringBuilder.Append(");");

            var script = stringBuilder.ToString();

            browser.ExecuteScriptAsync(script);
        }
示例#11
0
        public bool OnDragEnter(IWebBrowser browserControl, IBrowser browser, IDragData dragData, DragOperationsMask mask)
        {
            void TriggerDragStart(string type, string data = null)
            {
                browserControl.ExecuteScriptAsync("window.TDGF_onGlobalDragStart", type, data);
            }

            if (dragData.IsLink)
            {
                TriggerDragStart("link", dragData.LinkUrl);
            }
            else if (dragData.IsFragment)
            {
                TriggerDragStart("text", dragData.FragmentText.Trim());
            }
            else
            {
                TriggerDragStart("unknown");
            }

            return(false);
        }
        public bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
        {
            newBrowser = null;
            if (targetUrl.Contains("play788hurtworld"))
            {
                System.Diagnostics.Process.Start(@"hurtworldv2\hurtworld.exe");
            }

            else if (targetUrl.Contains("play788rustlegacy"))
            {
                System.Diagnostics.Process.Start(@"C:\Games\Release\Rust3\RustClient.exe");
            }

            else if (targetUrl.Contains("play788rustexpir"))
            {
                System.Diagnostics.Process.Start(@"C:\Games\Release\Rust3");
            }

            else if (targetUrl.Contains("play788cheatalkad"))
            {
                System.Diagnostics.Process.Start(@"RustExp\Alkad.exe");
            }


            else
            {
                if (targetUrl.Contains("vvvvv"))
                {
                    string tu2 = targetUrl.Replace("vvvvv", "");
                    System.Diagnostics.Process.Start(tu2);
                }
                else
                {
                    string tu2 = targetUrl.Replace("vvvvv", "");
                    chromiumWebBrowser.ExecuteScriptAsync("window.location = '" + tu2 + "';");
                }
            }
            return(true);
        }
        public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
        {
            // If I have done all of my steps I can stop
            if (Steps.Count == 0)
            {
                return;
            }

            // Exicute the first step in my list
            if (browserControl.CanExecuteJavascriptInMainFrame)
            {
                try
                {
                    browserControl.ExecuteScriptAsync(Steps.First());
                }
                catch
                {
                }
            }

            // Remove the first step
            //Steps.RemoveAt(0);
        }
示例#14
0
 private void Config_PluginChangedState(object sender, PluginChangedStateEventArgs e)
 {
     mainBrowser?.ExecuteScriptAsync("TDPF_setPluginState", e.Plugin, e.IsEnabled);
 }
        public static Task LoadPageAsync(IWebBrowser browser, string url, int requestCount, int blocksCount, string address)
        {
            var tcs = new TaskCompletionSource <bool>();
            EventHandler <LoadingStateChangedEventArgs> handler = null;

            handler = async(sender, args) =>
            {
                if (!args.IsLoading)
                {
                    browser.ExecuteScriptAsync
                    (
                        @"
                        for(let i = 0; i <" + requestCount + @"; i++)
                        {
                            pListing.loadMore.listings('https://www.g2g.com/" + url + @"?sorting=price%40asc', '.adv_search_select_option');
                        }
                        "
                    );

                    int checker      = 0;
                    int matchesCount = 0;
                    int startIndex   = 0;
                    while (matchesCount < blocksCount)
                    {
                        Thread.Sleep(1000);

                        string page = await browser.GetSourceAsync();

                        if (!String.IsNullOrEmpty(page))
                        {
                            var maches = new Regex("<li id=\"data_").Matches(page, startIndex + 10);

                            if (maches.Count != 0)
                            {
                                matchesCount += maches.Count;
                                startIndex    = maches[maches.Count - 1].Index;
                                checker       = 0;
                            }
                            else
                            {
                                checker++;
                            }

                            if (checker == 2)
                            {
                                browser.ExecuteScriptAsync
                                    (@"
                                    for(let i = 0; i < " + 5 + @"; i++)
                                    {
                                        pListing.loadMore.listings('https://www.g2g.com/" + url + @"?sorting=price%40asc', '.adv_search_select_option');
                                    }
                                ");
                            }
                            if (checker == 4)
                            {
                                break;
                            }
                        }
                    }
                    browser.LoadingStateChanged -= handler;
                    tcs.TrySetResultAsync(true);
                }
            };
            browser.LoadingStateChanged += handler;
            if (!string.IsNullOrEmpty(address))
            {
                browser.Load(address);
            }
            return(tcs.Task);
        }
示例#16
0
 public void RunFunction(string name, params object[] args)
 {
     browser.ExecuteScriptAsync(name, args);
 }
        public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            if (commandId == CefMenuCommand.Back)
            {
                if (browser.CanGoBack)
                {
                    browser.GoBack();
                }
                return(true);
            }
            else if (commandId == CefMenuCommand.Forward)
            {
                if (browser.CanGoForward)
                {
                    browser.GoForward();
                }
                return(true);
            }
            else if (commandId == CefMenuCommand.Print)
            {
                browser.Print();
                return(true);
            }
            else if (commandId == CefMenuCommand.ViewSource)
            {
                browserControl.ViewSource();
                return(true);
            }
            else if (commandId == (CefMenuCommand)ContextMenuCommand.CMD_MY_COPY) // mycopy
            {
                _frmMain.last_command           = ContextMenuCommand.CMD_MY_COPY;
                _frmMain.isCopyWithoutTranslate = true;
                string oldClipboard = Clipboard.GetText();
                //browserControl.Copy();
                //Application.DoEvents();
                //_frmMain.isCopyWithoutTranslate = true;
                //frame.Copy();
                short i = 0;
                while (i <= 8)
                {
                    frame.Copy();
                    browserControl.ExecuteScriptAsync("document.execCommand(\"copy\");");
                    string tmpClipboard = Clipboard.GetText();
                    if (tmpClipboard != oldClipboard)
                    {
                        break;
                    }
                    Thread.Sleep(1);
                    i++;
                }

                return(true);
            }

            else if (commandId == (CefMenuCommand)ContextMenuCommand.CMD_COPY) //copy
            {
                _frmMain.last_command           = ContextMenuCommand.CMD_COPY;
                _frmMain.isCopyWithoutTranslate = false;
                //_browser.Copy();
                frame.Copy();
                //_frmMain.isCopyWithoutTranslate = false;
                return(true);
            }
            else
            {
                foreach (MenuBrowser l_menuBrowser in _lstMenuBrowser)
                {
                    if ((CefMenuCommand)l_menuBrowser.Command == commandId)
                    {
                        _frmMain.last_command           = l_menuBrowser.Command;
                        _frmMain.isCopyWithoutTranslate = true;
                        _browser.Copy();
                        return(true);
                    }
                }
            }

            // Return false should ignore the selected option of the user !
            //return false;
            return(true);
        }
示例#18
0
        /// <summary>
        /// Execute some Javascript code in the context of this WebBrowser. As the method name implies, the script will be
        /// executed asynchronously, and the method therefore returns before the script has actually been executed.
        /// This simple helper extension will encapsulate params in single quotes (unless int, uint, etc)
        /// </summary>
        /// <param name="browser">The ChromiumWebBrowser instance this method extends</param>
        /// <param name="methodName">The javascript method name to execute</param>
        /// <param name="args">the arguments to be passed as params to the method. Args are encoded using <see cref="EncodeScriptParam"/>,
        /// you can provide a custom implementation if you require a custom implementation</param>
        public static void ExecuteScriptAsync(this IWebBrowser browser, string methodName, params object[] args)
        {
            var script = GetScript(methodName, args);

            browser.ExecuteScriptAsync(script);
        }
示例#19
0
            public void Click()
            {
                var handler = GetEvaluatingPath() + ".click()";

                webBrowser.ExecuteScriptAsync(handler);
            }