コード例 #1
0
        private async Task <string[]> GetBookAuthors()
        {
            var script = $"var eles = jQuery(\"{AUTHORS_SELECTOR}\");" +
                         "Array.prototype.join.call(eles.map(function(ele) { return this.textContent; } ), \",\");";
            var authorsInfo = (await _webMain.EvaluateScriptAsync(script, _timeout)).Result as string;

            return(string.IsNullOrWhiteSpace(authorsInfo) ? null : Regex.Split(authorsInfo, @"[,]"));
        }
コード例 #2
0
            public async Task RunTest()
            {
                InputState = TestStates.Running;
                var response = await _browser.EvaluateScriptAsync(InputJs);

                InputState    = response.Success ? TestStates.Passed : TestStates.Failed;
                InputJsResult = response.Result?.ToString() ?? "";
                if (InputState == TestStates.Failed)
                {
                    return;
                }
                var evalResponse = await _browser.EvaluateScriptAsync(EvaluateJs);

                ActualJavaScriptResult = evalResponse.Result?.ToString() ?? "";
                CheckState             = ActualJavaScriptResult == ExpectedJavaScriptResult ? TestStates.Passed : TestStates.Failed;
            }
コード例 #3
0
ファイル: LeafletTests.cs プロジェクト: LeafDotNet/LeafNet
        public static async Task <bool> Assert(IWebBrowser browser, string expected, string javascript)
        {
            var   script = browser.EvaluateScriptAsync("{ value = 2+2 }");
            await script;

            return(script.Result.Message == expected);
        }
コード例 #4
0
        private static async Task <bool> CheckForPagination(IWebBrowser browser)
        {
            bool isPagination = false;

            Task <JavascriptResponse> verifyPagination = browser.EvaluateScriptAsync(@"
                (function()
                 {
                    const element = document.getElementsByClassName('pagination')[0];
                    var listItem = element.getElementsByTagName('li');
                    for (var i=0; i < listItem.length; i++) {
                        if (listItem[i].textContent.includes('>')){
                            return true;
                        }
                    }
                    return false;
                 })();
                ");

            await verifyPagination.ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    var response = t.Result;
                    var EvaluateJavaScriptResult = response.Success ? (response.Result ?? "null") : response.Message;
                    isPagination = Convert.ToBoolean(response.Result);
                }
            }
                                                );

            return(isPagination);
        }
コード例 #5
0
        private static async Task <bool> CheckForResultsAsync(IWebBrowser browser)
        {
            bool isResult = false;
            Task <JavascriptResponse> verifyTable = browser.EvaluateScriptAsync(@"
                (function()
                 {
                    const element = document.getElementById('xxx');
                    if (element)
                        { return true; }
                    else
                        { return false; }
                 })();
                ");

            await verifyTable.ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    var response = t.Result;
                    var EvaluateJavaScriptResult = response.Success ? (response.Result ?? "null") : response.Message;
                    isResult = Convert.ToBoolean(response.Result);
                }
            }
                                           );

            return(isResult);
        }
コード例 #6
0
        /// <summary>
        /// 方法内部定义了死循环,用此循环来捕捉需要执行的js 代码
        /// </summary>
        private void InnerFlushScripts()
        {
            ScriptTask        scriptTask = null;
            List <ScriptTask> list       = new List <ScriptTask>();
            ScriptTask        scriptTask2;

            for (; ;)                //
            {
                scriptTask2 = this.pendingScripts.Take(this.flushTaskCancelationToken.Token);
                if (scriptTask2.WaitHandle != null)
                {
                    break;
                }
                list.Add(scriptTask2);
                if (this.pendingScripts.Count <= 0)
                {
                    goto IL_42;
                }
            }
            scriptTask = scriptTask2;
IL_42:
            if (list.Count > 0)
            {
                Task <JavascriptResponse> task = this.OwnerWebView.chromium.EvaluateScriptAsync(JavascriptExecutor.WrapScriptWithErrorHandling(string.Join(";" + Environment.NewLine, from s in list
                                                                                                                                                           select s.Script)), this.OwnerWebView.DefaultScriptsExecutionTimeout);
                task.Wait(this.flushTaskCancelationToken.Token);
                JavascriptResponse response = task.Result;
                if (!response.Success)
                {
                    this.OwnerWebView.ExecuteWithAsyncErrorHandling(delegate
                    {
                        throw JavascriptExecutor.ParseResponseException(response);
                    });
                }
            }
            if (scriptTask != null)
            {
                Task <JavascriptResponse> task2 = null;
                try
                {
                    IWebBrowser chromium = this.OwnerWebView.chromium;
                    string      script   = scriptTask.Script;
                    TimeSpan?   timeout  = scriptTask.Timeout;
                    task2 = chromium.EvaluateScriptAsync(script, (timeout != null) ? timeout : this.OwnerWebView.DefaultScriptsExecutionTimeout);
                    task2.Wait(this.flushTaskCancelationToken.Token);
                    scriptTask.Result = task2.Result;
                }
                catch (Exception exception)
                {
                    if (task2 == null || !task2.IsCanceled)
                    {
                        scriptTask.Exception = exception;
                    }
                }
                finally
                {
                    scriptTask.WaitHandle.Set();
                }
            }
        }
コード例 #7
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", "");
                }
            }
        }
コード例 #8
0
        private static string MainAsync(IWebBrowser browser, ref string url, TimeSpan timeout)
        {
            var tsk = LoadPageAsync(browser);

            tsk.Wait(new TimeSpan(0, 0, 30));
            if (tsk.IsCompleted)
            {
                url = tsk.Result;
                if (timeout.TotalMilliseconds > 0)
                {
                    var waitDone = new AutoResetEvent(false);
                    var th       = new Thread(new ParameterizedThreadStart((p) =>
                    {
                        var are = p as AutoResetEvent;
                        if (are != null)
                        {
                            Thread.Sleep((int)timeout.TotalMilliseconds);
                            are.Set();
                        }
                    }));
                    th.Start(waitDone);
                    //Task.Factory.StartNew(() => { Thread.Sleep((int)timeout.TotalMilliseconds); waitDone.Set(); });
                    waitDone.WaitOne();
                }
                var js = browser.EvaluateScriptAsync(@"document.getElementsByTagName('html')[0].innerHTML");
                js.Wait();
                return(js.Result.Result.ToString());
            }
            else
            {
                throw new Exception("Timeout");
            }
        }
コード例 #9
0
ファイル: TestLogic.cs プロジェクト: maleowy/ScrapTheWorld
        public static async Task Run1(this IWebBrowser browser) // Task Delay based
        {
            await Task.Delay(3000);

            browser.Load("https://duckduckgo.com");
            await Task.Delay(3000);

            await browser.EvaluateScriptAsync("document.querySelector('#search_form_input_homepage').value = 'Test';");

            await Task.Delay(1000);

            await browser.EvaluateScriptAsync("document.querySelector('#search_button_homepage').click();");

            await Task.Delay(1000);

            await browser.EvaluateScriptAsync("console.log(document.title)");
        }
コード例 #10
0
ファイル: CSharpBus.cs プロジェクト: grodnonetcommunity/Cef
        private async Task <string> AlertCore(string message)
        {
            await Task.Delay(2000).ConfigureAwait(false);

            await _browser.EvaluateScriptAsync($"alert('{message}');").ConfigureAwait(false);

            return("Done");
        }
コード例 #11
0
ファイル: TestLogic.cs プロジェクト: maleowy/ScrapTheWorld
        public static async Task Run(this IWebBrowser browser) // better one
        {
            await browser.WaitForInitializationAsync();

            await browser.LoadPageAsync("https://duckduckgo.com");

            await browser.EvaluateScriptAsync("document.querySelector('#search_form_input_homepage').value = 'Test';");

            await browser.EvaluateScriptAsync("document.querySelector('#search_button_homepage').click();");

            await browser.LoadPageAsync();

            string title = await browser.EvaluateScriptWithReturnAsync("document.title");

            await browser.EvaluateScriptAsync("console.log(document.title)");

            await browser.EvaluateScriptAsync("bound.reverseText(document.title)");
        }
コード例 #12
0
        public async Task <string> EvaluateJavaScript(string text)
        {
            var result = await _browser.EvaluateScriptAsync(text);

            if (!result.Success)
            {
                throw new Exception(result.Message);
            }

            return((string)result.Result);
        }
        public Task <ScriptRunResult> RunWithResult(string script)
        {
            var task = _browser.EvaluateScriptAsync(script);

            return(task.ContinueWith(task1 => new ScriptRunResult()
            {
                Success = task1.Result.Success,
                Result = task1.Result.Result,
                Message = task1.Result.Message
            }));
        }
コード例 #14
0
            public string GetAttribute(string name)
            {
                var handler = GetEvaluatingPath() + ".getAttribute('" + name + "')";
                var result  = webBrowser.EvaluateScriptAsync(handler).Result;

                if (!result.Success)
                {
                    throw new InvalidOperationException(string.Format("Unable to get the attribute with the name {0} on the element", name));
                }
                return(result.Result.ToString());
            }
コード例 #15
0
        private static async Task Scrap(IWebBrowser browser)
        {
            await SaveNumberToFileAsync();

            await browser.EvaluateScriptAsync(@"
			document.getElementById('xxx').value = '"             + _min + @"';
			document.getElementById('xxx').value = '"             + _max + @"';
			document.getElementById('buttonAdvSearch').click();
            ");

            await VerifyResults(browser);
        }
コード例 #16
0
        public void FetchMessageFromBrowser()
        {
            var task = _browser.EvaluateScriptAsync("window.applicationInterface.loadText();");

            task.ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    var response = t.Result;
                    MessageText  = response.Success ? ((string)response.Result ?? String.Empty) : response.Message;
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
コード例 #17
0
        private static async Task LoadNextPage(IWebBrowser browser)
        {
            await browser.EvaluateScriptAsync(@"
			const element = document.getElementsByClassName('pagination')[0];
            var listItem = element.getElementsByTagName('li');
            for (var i = 0; i < listItem.length; i++)
            {
                if (listItem[i].textContent.includes('>')){
                    listItem[i].children[0].click();
                }
            }
            ");
        }
コード例 #18
0
ファイル: Script.cs プロジェクト: LeafDotNet/LeafNet
        public static async Task <string> EvaluateJavaScript(string s, IWebBrowser webBrowser)
        {
            try
            {
                var response = await webBrowser.EvaluateScriptAsync(s);

                if (response.Success && response.Result is IJavascriptCallback)
                {
                    response = await((IJavascriptCallback)response.Result).ExecuteAsync("This is a callback from EvaluateJavaScript");
                }
                return(response.Success ? (JsonConvert.SerializeObject(response.Result, Formatting.Indented) ?? "null") : response.Message);
            }
            catch (Exception e)
            {
                MessageBox.Show("Error while evaluating Javascript: " + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            return("exception");
        }
コード例 #19
0
        public async Task <bool> Load(Beatmap beatmap)
        {
            if (beatmap == null)
            {
                throw new ArgumentNullException();
            }

            string mapJson  = JsonSerializer.Serialize(beatmap.Metadata, _serializerOptions);
            string musicBin = Convert.ToBase64String(beatmap.Music);

            string script   = $"Sparebeat.load({mapJson}, '{musicBin}')";
            var    response = await _browser.EvaluateScriptAsync(script);

            if (response.Success)
            {
                _snapshot.BeginInvokeEvent(BeatmapChanged, this, beatmap);
            }

            return(response.Success);
        }
コード例 #20
0
        public async void RunUnitTests()
        {
            foreach (var unitTest in UnitTests)
            {
                var script = await _browser.EvaluateScriptAsync(unitTest.JavaScript);

                _dispatcher.Invoke(() =>
                {
                    if (!script.Success)
                    {
                        unitTest.Passed = PassState.Failed;
                    }
                    else
                    {
                        unitTest.ActualResult = script.Result?.ToString();
                        unitTest.Passed       = unitTest.ActualResult == unitTest.ExpectedResult ? PassState.Passed :  PassState.Failed;
                    }
                });
            }
        }
コード例 #21
0
        /// <summary>
        /// Evaluate some Javascript code in the context of this WebBrowser using the specified timeout. The script will be executed asynchronously and the
        /// method returns a Task encapsulating the response from the Javascript
        /// 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="timeout">The timeout after which the Javascript code execution should be aborted.</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>
        /// <returns><see cref="Task{JavascriptResponse}"/> that can be awaited to perform the script execution</returns>
        public static Task <JavascriptResponse> EvaluateScriptAsync(this IWebBrowser browser, TimeSpan?timeout, string methodName, params object[] args)
        {
            var script = GetScript(methodName, args);

            return(browser.EvaluateScriptAsync(script, timeout));
        }
コード例 #22
0
 /// <summary>
 /// Evaluate some Javascript code in the context of this WebBrowser. The script will be executed asynchronously and the
 /// method returns a Task encapsulating the response from the Javascript
 /// 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>
 /// <returns><see cref="Task{JavascriptResponse}"/> that can be awaited to perform the script execution</returns>
 public static Task <JavascriptResponse> EvaluateScriptAsync(this IWebBrowser browser, string methodName, params object[] args)
 {
     return(browser.EvaluateScriptAsync(null, methodName, args));
 }
コード例 #23
0
 private static async Task <T> EvaluateWithReturnAsync <T>(IWebBrowser browser, string script, TimeSpan?timeout, T defaultValue)
 {
     return(await browser.EvaluateScriptAsync(script, timeout)
            .ContinueWith(x => !x.IsFaulted && x.Result.Success ? (T)x.Result.Result : defaultValue));
 }
コード例 #24
0
        public async Task <string> Execute(string script, string sourceUrl)
        {
            var res = await _webBrowser.EvaluateScriptAsync(script);

            return("{0}".ToFormat(res.Result));
        }
コード例 #25
0
ファイル: CEFLoader.cs プロジェクト: kblc/ExcelConverter
 private static string MainAsync(IWebBrowser browser, ref string url, TimeSpan timeout)
 {
     var tsk = LoadPageAsync(browser);
     tsk.Wait(new TimeSpan(0, 0, 30));
     if (tsk.IsCompleted)
     {
         url = tsk.Result;
         if (timeout.TotalMilliseconds > 0)
         {
             var waitDone = new AutoResetEvent(false);
             var th = new Thread(new ParameterizedThreadStart((p) =>
             {
                 var are = p as AutoResetEvent;
                 if (are != null)
                 {
                     Thread.Sleep((int)timeout.TotalMilliseconds);
                     are.Set();
                 }
             }));
             th.Start(waitDone);
             //Task.Factory.StartNew(() => { Thread.Sleep((int)timeout.TotalMilliseconds); waitDone.Set(); });
             waitDone.WaitOne();
         }
         var js = browser.EvaluateScriptAsync(@"document.getElementsByTagName('html')[0].innerHTML");
         js.Wait();
         return js.Result.Result.ToString();
     }
     else
         throw new Exception("Timeout");
 }
            public async Task <dynamic> Evaluate(string s)
            {
                var result = await _browser.EvaluateScriptAsync(s).ConfigureAwait(false);

                return(result);
            }