Example #1
0
        public virtual void doActions(List <WebAction> actions)
        {
            completedEventHandler         = new WebBrowserDocumentCompletedEventHandler(this.pageLoaded);
            WebBrowser.DocumentCompleted += completedEventHandler;
            Queue <WebAction> activeActions = new Queue <WebAction>(actions);

            while (0 < activeActions.Count)
            {
                activeAction = activeActions.Dequeue();
                if (activeAction.canDoAction(this))
                {
                    if (activeAction.shouldWaitAction(this))
                    {
                        trigger.Reset();
                        WaitHandle.WaitAny(waitHandles);
                    }
                    activeAction.doAction(this);
                    if (activeAction.isWaitForEvent())
                    {
                        trigger.Reset();
                        WaitHandle.WaitAny(waitHandles);
                    }
                }
            }
            completedActions();
        }
        private async void MainForm_Load(object sender, EventArgs e)
        {
            var wb = new WebBrowser();

            TaskCompletionSource <bool>             tcs = null;
            WebBrowserDocumentCompletedEventHandler documentCompletedHandler = (sender2, e2) => tcs.TrySetResult(true);

            for (int i = 0; i < 3; i++)
            {
                tcs = new TaskCompletionSource <bool>();
                wb.DocumentCompleted += documentCompletedHandler;
                try {
                    wb.DocumentText = leMessage;
                    await tcs.Task;
                }
                finally {
                    wb.DocumentCompleted -= documentCompletedHandler;
                }
                HtmlElementCollection elems = wb.Document.GetElementsByTagName("a");
                foreach (HtmlElement elem in elems)
                {
                    Debug.Print(elem.OuterHtml);
                }
            }
        }
Example #3
0
 public virtual void doActions(List <WebAction> actions)
 {
     completedEventHandler         = new WebBrowserDocumentCompletedEventHandler(this.pageLoaded);
     WebBrowser.DocumentCompleted += completedEventHandler;
     activeActions = new Queue <WebAction>(actions);
     doNextAction();
 }
Example #4
0
        /// <summary>
        ///
        /// </summary>
        private void Download()
        {
            try
            {
                CanDownload = false;
                var downloader = _options[SelectedTab].Value;
                var site       = Utilities.GetWebsite(downloader.Url);
                var browser    = new WebBrowser
                {
                    ScriptErrorsSuppressed = true,
                    AllowNavigation        = true
                };

                browser.Navigate(new Uri(downloader.Url));
                WebBrowserDocumentCompletedEventHandler handler = null;
                handler = (sender, args) =>
                {
                    browser.DocumentCompleted -= handler;
                    _downloaders[site].Invoke(sender, args, site, downloader);
                };

                browser.DocumentCompleted += handler;
            }
            catch (WebException)
            {
                MessageBox.Show("Error downloading", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                CanDownload = true;
            }
            catch (InvalidUrlException ex)
            {
                MessageBox.Show(string.Format("{0}\n\nUrl: {1}", ex.Message, ex.Url), "Invalid Url", MessageBoxButton.OK, MessageBoxImage.Error);
                CanDownload = true;
            }
        }
        private async Task DoNavigationAsync()
        {
            TaskCompletionSource <bool> documentCompleteTcs = null;

            WebBrowserDocumentCompletedEventHandler handler = delegate
            {
                if (documentCompleteTcs.Task.IsCompleted)
                {
                    return;
                }
                documentCompleteTcs.SetResult(true);
            };

            documentCompleteTcs        = new TaskCompletionSource <bool>();
            this.wb.DocumentCompleted += handler;

            // could do this.wb.Navigate(url) here
            this.wb.DocumentText = "<!DOCTYPE html><head><meta http-equiv='X-UA-Compatible' content='IE=edge'/></head>" +
                                   "<body><input size=50 type='text' placeholder='HTML5 if this placeholder is visible'/></body>";

            await documentCompleteTcs.Task;

            this.wb.DocumentCompleted -= handler;

            dynamic document  = this.wb.Document.DomDocument;
            dynamic navigator = document.parentWindow.navigator;
            var     info      =
                "\n navigator.userAgent: " + navigator.userAgent +
                "\n navigator.appName: " + navigator.appName +
                "\n document.documentMode: " + document.documentMode +
                "\n document.compatMode: " + document.compatMode;

            MessageBox.Show(info);
        }
Example #6
0
        public async Task NextPageAsync(string url)
        {
            _currentUrl = url;

            // _currentPage = await _apartment.Run(() => _browser.NavigateAsync(_currentUrl, navigationToken), navigationToken);
            _currentPage = await _apartment.Run(async() =>
            {
                WebBrowserDocumentCompletedEventHandler handler = null;
                var navigateTcs = new TaskCompletionSource <bool>();
                handler         = (s, e) =>
                                  navigateTcs.TrySetResult(true);
                _browser.DocumentCompleted += handler;
                try
                {
                    using (_cancelToken.Register(() => navigateTcs.TrySetCanceled()))
                    {
                        _browser.Navigate(url);
                        await navigateTcs.Task;
                        return(_browser.Document.Body.OuterHtml);
                    }
                }
                finally
                {
                    _browser.DocumentCompleted -= handler;
                }
            },
                                                _cancelToken);
        }
Example #7
0
        // navigate WebBrowser to the list of urls in a loop
        static async Task <object> DoWorkAsync(object[] args)
        {
            Console.WriteLine("Start working.");

            var wb = new WebBrowser();

            wb.ScriptErrorsSuppressed = true;

            TaskCompletionSource <bool>             tcs = null;
            WebBrowserDocumentCompletedEventHandler documentCompletedHandler = (s, e) =>
                                                                               tcs.TrySetResult(true);

            // navigate to each URL in the list
            foreach (var url in args)
            {
                tcs = new TaskCompletionSource <bool>();
                wb.DocumentCompleted += documentCompletedHandler;
                try
                {
                    wb.Navigate(url.ToString());
                    // await for DocumentCompleted
                    await tcs.Task;
                }
                finally
                {
                    wb.DocumentCompleted -= documentCompletedHandler;
                }
                // the DOM is ready
                Console.WriteLine(url.ToString());
                Console.WriteLine(wb.Document.Body.OuterHtml);
            }

            Console.WriteLine("End working.");
            return(null);
        }
Example #8
0
        public static async Task <Bitmap> RenderApiDump(string htmlFilePath)
        {
            var    docReady = new WebBrowserDocumentCompletedEventHandler(onDocumentComplete);
            string fileUrl  = "file://" + htmlFilePath.Replace('\\', '/');

            Thread renderThread = new Thread(() =>
            {
                var renderer = new WebBrowser()
                {
                    Url = new Uri(fileUrl),
                    ScrollBarsEnabled = false,
                };

                renderer.DocumentCompleted += docReady;
                Application.Run();
            });

            renderFinished = new TaskCompletionSource <Bitmap>();

            renderThread.SetApartmentState(ApartmentState.STA);
            renderThread.Start();

            await renderFinished.Task;
            var apiRender = renderFinished.Task.Result;

            return(apiRender);
        }
Example #9
0
        void MainForm_Load(object senderLoad, EventArgs eLoad)
        {
            using (var apartment = new MessageLoopApartment())
            {
                // create WebBrowser on a seprate thread with its own message loop
                var webBrowser = apartment.Run(() => new WebBrowser(), CancellationToken.None).Result;

                // navigate and wait for the result

                var bodyHtml = apartment.Invoke(() =>
                {
                    WebBrowserDocumentCompletedEventHandler handler = null;
                    var pageLoadedTcs = new TaskCompletionSource <string>();
                    handler           = (s, e) =>
                    {
                        try
                        {
                            webBrowser.DocumentCompleted -= handler;
                            pageLoadedTcs.SetResult(webBrowser.Document.Body.InnerHtml);
                        }
                        catch (Exception ex)
                        {
                            pageLoadedTcs.SetException(ex);
                        }
                    };

                    webBrowser.DocumentCompleted += handler;
                    webBrowser.Navigate("http://example.com");

                    // return Task<string>
                    return(pageLoadedTcs.Task);
                }).Result;

                MessageBox.Show("body content:\n" + bodyHtml);

                // execute some JavaScript

                var documentHtml = apartment.Invoke(() =>
                {
                    // at least one script element must be present for eval to work
                    var scriptElement = webBrowser.Document.CreateElement("script");
                    webBrowser.Document.Body.AppendChild(scriptElement);

                    // inject and run some script
                    var scriptResult = webBrowser.Document.InvokeScript("eval", new[] {
                        "(function(){ return document.documentElement.outerHTML; })();"
                    });

                    return(scriptResult.ToString());
                });

                MessageBox.Show("document content:\n" + documentHtml);

                // dispose of webBrowser
                apartment.Run(() => webBrowser.Dispose(), CancellationToken.None).Wait();
                webBrowser = null;
            }
        }
Example #10
0
        protected virtual void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowserDocumentCompletedEventHandler handler = (WebBrowserDocumentCompletedEventHandler)this.Events[DocumentCompletedEventKey];

            if (handler != null)
            {
                handler(this, e);
            }
        }
Example #11
0
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// webbrowserdocumentcompletedeventhandler.BeginInvoke(sender, e, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this WebBrowserDocumentCompletedEventHandler webbrowserdocumentcompletedeventhandler, Object sender, WebBrowserDocumentCompletedEventArgs e, AsyncCallback callback)
        {
            if (webbrowserdocumentcompletedeventhandler == null)
            {
                throw new ArgumentNullException("webbrowserdocumentcompletedeventhandler");
            }

            return(webbrowserdocumentcompletedeventhandler.BeginInvoke(sender, e, callback, null));
        }
Example #12
0
        // navigate and download
        async Task <string> LoadDynamicPage(string url, CancellationToken token)
        {
            // navigate and await DocumentCompleted
            var tcs = new TaskCompletionSource <bool>();
            WebBrowserDocumentCompletedEventHandler handler = (s, arg) =>
                                                              tcs.TrySetResult(true);

            WebBrowser webBrowser = new WebBrowser();

            webBrowser.ScriptErrorsSuppressed = true;
            webBrowser.ObjectForScripting     = true;
            SetFeatureBrowserEmulation();

            using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true))
            {
                webBrowser.DocumentCompleted += handler;
                try
                {
                    webBrowser.Navigate(url);
                    await tcs.Task; // wait for DocumentCompleted
                }
                finally
                {
                    webBrowser.DocumentCompleted -= handler;
                }
            }

            // get the root element
            var documentElement = webBrowser.Document.GetElementsByTagName("html")[0];

            // poll the current HTML for changes asynchronosly
            var html = documentElement.OuterHtml;

            while (true)
            {
                // wait asynchronously, this will throw if cancellation requested
                await Task.Delay(500, token);

                // continue polling if the WebBrowser is still busy
                if (webBrowser.IsBusy)
                {
                    continue;
                }

                var htmlNow = documentElement.OuterHtml;
                if (html == htmlNow)
                {
                    break; // no changes detected, end the poll loop
                }
                html = htmlNow;
            }

            // consider the page fully rendered
            token.ThrowIfCancellationRequested();
            return(html);
        }
 public void setDocumentLoadHandler(Action <object, WebBrowserDocumentCompletedEventArgs> func)
 {
     //Remove the old event listener
     if (oldEventHandle != null)
     {
         webBrowser1.DocumentCompleted -= oldEventHandle;
     }
     oldEventHandle = new WebBrowserDocumentCompletedEventHandler(func);
     webBrowser1.DocumentCompleted += oldEventHandle;
 }
Example #14
0
        protected virtual void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowserDocumentCompletedEventHandler completedEventHandler = (WebBrowserDocumentCompletedEventHandler)this.Events[RadWebBrowserItem.DocumentCompletedEventKey];

            if (completedEventHandler == null)
            {
                return;
            }
            completedEventHandler((object)this, e);
        }
Example #15
0
        static Task <WebBrowser> runInternal(Action action, Func <bool> QuitCondition)
        {
            try
            {
                var t  = new TaskCompletionSource <WebBrowser>();
                var ie = ApplyContext.Current.IE;

                //如果有退出条件,检查
                if (QuitCondition != null)
                {
                    var timer = new Timer(state =>
                    {
                        bool result;

                        if (ie.InvokeRequired && ie.Created)
                        {
                            result = (bool)ie.Invoke(QuitCondition);
                        }
                        else
                        {
                            result = QuitCondition();
                        }

                        if (result)
                        {
                            t.TrySetResult(ie);
                            (state as Timer).Dispose();
                        }
                    });
                    timer.Change(1000, 1000);
                }

                WebBrowserDocumentCompletedEventHandler callBack = null;
                callBack = (o, e) =>
                {
                    if (e.Url == ie.Url && ie.ReadyState == WebBrowserReadyState.Complete)
                    {
                        t.TrySetResult(ie);
                        ie.DocumentCompleted -= callBack;
                    }
                };
                ie.DocumentCompleted += callBack;

                if (action != null)
                {
                    action();
                }
                return(t.Task);
            }
            catch (Exception ex)
            {
                ApplyContext.Current.ShowMessage(ex.Message);
                throw;
            }
        }
Example #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// <param name="site"></param>
        /// <param name="options"></param>
        private void EHentaiBrowserOnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs args, Website site, WebsiteOptions options)
        {
            var browser = (WebBrowser)sender;

            if (browser.Document?.Body == null)
            {
                return;
            }

            var title = _formatters[site].Invoke(browser.DocumentTitle);

            Debug.WriteLine(title);
            var folder = Path.Combine(options.Folder, title);

            Directory.CreateDirectory(folder);

            var links = browser.Document.GetElementsByTagName("a")
                        .OfType <HtmlElement>()
                        .Where(e =>
            {
                var href = e.GetAttribute("href");
                if (string.IsNullOrEmpty(href) || href.Length <= 2)
                {
                    return(false);
                }

                return
                ((href[href.Length - 2] == '-' ||
                  href[href.Length - 3] == '-' ||
                  href[href.Length - 4] == '-') &&
                 href.StartsWith("https://e-hentai.org/s/"));
            })
                        .Select(e => e.GetAttribute("href"))
                        .ToList();

            foreach (var link in links)
            {
                var browser1 = new WebBrowser
                {
                    ScriptErrorsSuppressed = true,
                    AllowNavigation        = true
                };

                WebBrowserDocumentCompletedEventHandler handler = null;
                var link1 = link;
                handler = (s, a) =>
                {
                    browser1.DocumentCompleted -= handler;
                    ProcessEHentaiPage(s, folder, link1.Substring(link1.LastIndexOf('-') + 1), links.Count);
                };

                browser1.DocumentCompleted += handler;
                browser1.Url = new Uri(link);
            }
        }
Example #17
0
 public virtual void init()
 {
     RequestContext = new Dictionary <string, object>();
     Outputs        = new Dictionary <string, object>();
     if (MonitorTimings)
     {
         completedEventHandlerForTiming = new WebBrowserDocumentCompletedEventHandler(this.pageLoadedForMonitoring);
         WebBrowser.DocumentCompleted  += completedEventHandlerForTiming;
         AccessTimes = new Stack <AccessTiming>();
     }
 }
Example #18
0
        public static async Task <string> GetLocationChangeAsync(this WebBrowser webBrowser, string url, CancellationToken token)
        {
            // navigate and await DocumentCompleted
            var tcs = new TaskCompletionSource <bool>();
            WebBrowserDocumentCompletedEventHandler handler = (s, arg) =>
                                                              tcs.TrySetResult(true);

            using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true))
            {
                webBrowser.DocumentCompleted += handler;
                try
                {
                    webBrowser.Navigate(url);
                    await tcs.Task; // wait for DocumentCompleted
                }
                finally
                {
                    webBrowser.DocumentCompleted -= handler;
                }
            }

            // get the root element
            var    documentElement = webBrowser.Document.GetElementsByTagName("html")[0];
            string browserUrl      = webBrowser.Url.ToString();

            if (browserUrl != url)
            {
                return(browserUrl);                   //location has already changed
            }
            // poll the current location url for changes asynchronosly
            while (true)
            {
                // wait asynchronously, this will throw if cancellation requested
                await Task.Delay(POLL_DELAY, token);

                // continue polling if the WebBrowser is still busy
                if (webBrowser.IsBusy)
                {
                    continue;
                }

                string browserUrlNow = webBrowser.Url.ToString();
                if (browserUrl != browserUrlNow) //change detected
                {
                    browserUrl = browserUrlNow;
                    break;
                }
            }

            // consider the page fully rendered
            token.ThrowIfCancellationRequested();
            return(browserUrl);
        }
    public static Task <Uri> DocumentCompletedAsync(this WebBrowser wb)
    {
        var tcs = new TaskCompletionSource <Uri>();
        WebBrowserDocumentCompletedEventHandler handler = null;

        handler = (_, e) =>
        {
            wb.DocumentCompleted -= handler;
            tcs.TrySetResult(e.Url);
        };
        wb.DocumentCompleted += handler;
        return(tcs.Task);
    }
Example #20
0
        public static async Task <bool> GetPageAsImageAsync(string url, string path)
        {
            var tcs = new TaskCompletionSource <bool>();
            //await TaskEx.Delay(1);

            var thread = new Thread(() =>
            {
                using (var browser = new WebBrowser())
                {
                    browser.Size = new Size(1280, 768);
                    browser.ScrollBarsEnabled = false;
                    WebBrowserDocumentCompletedEventHandler documentCompleted = null;
                    documentCompleted = async(o, s) =>
                    {
                        var loadedBrowser = (WebBrowser)o;
                        loadedBrowser.DocumentCompleted -= documentCompleted;
                        await TaskEx.Delay(2000); //Run JS a few seconds more

                        if (loadedBrowser.Document != null)
                        {
                            if (loadedBrowser.Document.Body != null)
                            {
                                loadedBrowser.Width  = loadedBrowser.Document.Body.ScrollRectangle.Width;
                                loadedBrowser.Height = loadedBrowser.Document.Body.ScrollRectangle.Height;
                            }
                        }

                        using (var bitmap = new Bitmap(loadedBrowser.Width, loadedBrowser.Height))
                        {
                            loadedBrowser.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
                            bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                        }
                        System.Windows.Forms.Application.Exit();
                        tcs.TrySetResult(true);
                    };

                    browser.ScriptErrorsSuppressed = true;
                    browser.DocumentCompleted     += documentCompleted;
                    browser.Navigate(url);
                    System.Windows.Forms.Application.Run();
                }
                //IntPtr pHandle = GetCurrentProcess();
                //SetProcessWorkingSetSize(pHandle, -1, -1);
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            System.Threading.Thread.SpinWait(3000);

            return(tcs.Task.Result);
        }
Example #21
0
        // asynchronous navigation
        async Task <string> NavigateAsync(CancellationToken ct, Action startNavigation)
        {
            var          onloadTcs          = new TaskCompletionSource <bool>();
            EventHandler onloadEventHandler = null;

            WebBrowserDocumentCompletedEventHandler documentCompletedHandler = delegate
            {
                // DocumentCompleted may be called several time for the same page,
                // if the page has frames
                if (onloadEventHandler != null)
                {
                    return;
                }

                // so, observe DOM onload event to make sure the document is fully loaded
                onloadEventHandler = (s, e) =>
                                     onloadTcs.TrySetResult(true);
                this.webBrowser.Document.Window.AttachEventHandler("onload", onloadEventHandler);
            };

            this.webBrowser.DocumentCompleted += documentCompletedHandler;
            try
            {
                using (ct.Register(() => onloadTcs.TrySetCanceled(), useSynchronizationContext: true))
                {
                    startNavigation();
                    // wait for DOM onload event, throw if cancelled
                    await onloadTcs.Task;
                }
            }
            finally
            {
                this.webBrowser.DocumentCompleted -= documentCompletedHandler;
                if (onloadEventHandler != null)
                {
                    this.webBrowser.Document.Window.DetachEventHandler("onload", onloadEventHandler);
                }
            }

            // the page has fully loaded by now

            // optional: let the page run its dynamic AJAX code,
            // we might add another timeout for this loop
            do
            {
                await Task.Delay(500, ct);
            }while (this.webBrowser.IsBusy);

            // return the page's HTML content
            return(this.webBrowser.Document.GetElementsByTagName("html")[0].OuterHtml);
        }
Example #22
0
        // navigate and download
        public static async Task <string> NavigateAsync(this WebBrowser webBrowser, string url, string targetFrameName, byte[] postData, string additionalHeaders, CancellationToken token)
        {
            // navigate and await DocumentCompleted
            var tcs = new TaskCompletionSource <bool>();
            WebBrowserDocumentCompletedEventHandler handler = (s, arg) =>
                                                              tcs.TrySetResult(true);

            using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true))
            {
                webBrowser.DocumentCompleted += handler;
                try
                {
                    webBrowser.Navigate(url, targetFrameName, postData, additionalHeaders);
                    await tcs.Task; // wait for DocumentCompleted
                }
                finally
                {
                    webBrowser.DocumentCompleted -= handler;
                }
            }

            // get the root element
            var documentElement = webBrowser.Document.GetElementsByTagName("html")[0];

            // poll the current HTML for changes asynchronosly
            var html = documentElement.OuterHtml;

            while (true)
            {
                // wait asynchronously, this will throw if cancellation requested
                await Task.Delay(POLL_DELAY, token);

                // continue polling if the WebBrowser is still busy
                if (webBrowser.IsBusy)
                {
                    continue;
                }

                var htmlNow = documentElement.OuterHtml;
                if (html == htmlNow)
                {
                    break; // no changes detected, end the poll loop
                }
                html = htmlNow;
            }

            // consider the page fully rendered
            token.ThrowIfCancellationRequested();
            return(html);
        }
Example #23
0
        // Async navigation
        public async Task NavigateAsync(CancellationToken ct, Action startNavigation, int timeout = Timeout.Infinite)
        {
            var          onloadTcs          = new TaskCompletionSource <bool>();
            EventHandler onloadEventHandler = null;

            WebBrowserDocumentCompletedEventHandler documentCompletedHandler = delegate
            {
                // DocumentCompleted may be called several time for the same page,
                // beacuse of frames
                if (onloadEventHandler != null || onloadTcs == null || onloadTcs.Task.IsCompleted)
                {
                    return;
                }

                // handle DOM onload event to make sure the document is fully loaded
                onloadEventHandler = (s, e) =>
                                     onloadTcs.TrySetResult(true);
                this.webBrowser.Document.Window.AttachEventHandler("onload", onloadEventHandler);
            };

            using (var cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
            {
                if (timeout != Timeout.Infinite)
                {
                    cts.CancelAfter(Timeout.Infinite);
                }

                using (cts.Token.Register(() => onloadTcs.TrySetCanceled(), useSynchronizationContext: true))
                {
                    this.webBrowser.DocumentCompleted += documentCompletedHandler;
                    try
                    {
                        startNavigation();
                        // wait for DOM onload, throw if cancelled
                        await onloadTcs.Task;
                        ct.ThrowIfCancellationRequested();
                        // let AJAX code run, throw if cancelled
                        await Task.Delay(AJAX_DELAY, ct);
                    }
                    finally
                    {
                        this.webBrowser.DocumentCompleted -= documentCompletedHandler;
                        if (onloadEventHandler != null)
                        {
                            this.webBrowser.Document.Window.DetachEventHandler("onload", onloadEventHandler);
                        }
                    }
                }
            }
        }
             private TaskAwaiter<string> ProcessUrlAwaitable(WebBrowser webBrowser, string url)
             {
                 TaskCompletionSource<string> taskCompletionSource = new TaskCompletionSource<string>();
                 var handler = new WebBrowserDocumentCompletedEventHandler((s, e) =>
                 {
                     // TODO: put custom processing of document here
                     taskCompletionSource.SetResult(e.Url + ": " + webBrowser.Document.Title);
                 });
                 webBrowser.DocumentCompleted += handler;
                 taskCompletionSource.Task.ContinueWith(s => { webBrowser.DocumentCompleted -= handler; });
 
                 webBrowser.Navigate(url);
                 return taskCompletionSource.Task.GetAwaiter();
             }
        // this code depends on SHDocVw.dll COM interop assembly,
        // generate SHDocVw.dll: "tlbimp.exe ieframe.dll",
        // and add as a reference to the project

        private async void MainForm_Load(object sender, EventArgs e)
        {
            // make sure the ActiveX has been created
            if ((this.webBrowser.Document == null && this.webBrowser.ActiveXInstance == null))
            {
                throw new ApplicationException("webBrowser");
            }

            // handle NewWindow
            var activex = (SHDocVw.WebBrowser_V1) this.webBrowser.ActiveXInstance;

            activex.NewWindow += delegate(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed)
            {
                Processed = true;

                object flags       = Flags;
                object targetFrame = Type.Missing;
                object postData    = PostData != null ? PostData : Type.Missing;
                object headers     = !String.IsNullOrEmpty(Headers) ? Headers.ToString() : Type.Missing;

                SynchronizationContext.Current.Post(delegate
                {
                    activex.Navigate(URL, ref flags, ref targetFrame, ref postData, ref headers);
                }, null);
            };

            // navigate to a stream
            using (var stream = new MemoryStream())
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(HTML_DATA);
                    writer.Flush();
                    stream.Position = 0;

                    // naviage and await DocumentCompleted
                    var tcs = new TaskCompletionSource <bool>();
                    WebBrowserDocumentCompletedEventHandler handler = (s, arg) =>
                                                                      tcs.TrySetResult(true);
                    this.webBrowser.DocumentCompleted += handler;
                    this.webBrowser.DocumentStream     = stream;
                    await tcs.Task;
                    this.webBrowser.DocumentCompleted -= handler;
                }

            // click the button
            var button = this.webBrowser.Document.GetElementById("go");

            button.InvokeMember("click");
        }
    public static Task SetDocumentTextAsync(this WebBrowser wb, string html)
    {
        TaskCompletionSource <object>           tcs            = new TaskCompletionSource <object>();
        WebBrowserDocumentCompletedEventHandler completedEvent = null;

        completedEvent = (sender, e) =>
        {
            wb.DocumentCompleted -= completedEvent;
            tcs.SetResult(null);
        };
        wb.DocumentCompleted     += completedEvent;
        wb.ScriptErrorsSuppressed = true;
        wb.DocumentText           = html;
        return(tcs.Task);
    }
Example #27
0
    public static Task <Uri> DocumentCompletedAsync(this WebBrowser wb, int timeout)
    {
        var tcs = new TaskCompletionSource <Uri>();
        WebBrowserDocumentCompletedEventHandler handler = null;
        var timeoutRegistration = WithTimeout(tcs, timeout,
                                              () => wb.DocumentCompleted -= handler);

        handler = (_, e) =>
        {
            wb.DocumentCompleted -= handler;
            timeoutRegistration.Unregister();
            tcs.TrySetResult(e.Url);
        };
        wb.DocumentCompleted += handler;
        return(tcs.Task);
    }
Example #28
0
        private void BrowseToResource(Renderable render)
        {
            WebBrowserDocumentCompletedEventHandler completedHandler = null;
            string html, script;

            this.SelectResources(render, out html, out script);

            completedHandler = (sender, e) => {
                this.StopListeningAndAddCommonHtmlElements(completedHandler);
                this.AddScriptElement(script);
                this.Render(render);
            };

            this.AllowNavigation    = true;
            this.DocumentCompleted += completedHandler;
            this.DocumentText       = html;
        }
Example #29
0
        private void StopListeningAndAddCommonHtmlElements(WebBrowserDocumentCompletedEventHandler completedHandler)
        {
            // ordering of the following is IMPORTANT
            // stop listening
            this.AllowNavigation    = false;
            this.DocumentCompleted -= completedHandler;

            // load our css in
            this.AddStyleSheet(Properties.Resources.statblock_css);

            // load our javascript in
            this.AddScriptElement(Properties.Resources.modernizr_2_6_2_js);
            this.AddScriptElement(Properties.Resources.underscore_js);
            this.AddScriptElement(Properties.Resources.knockout_3_0_0_debug_js);
            this.AddScriptElement(Properties.Resources.knockout_StringInterpolatingBindingProvider_js);
            this.AddScriptElement(Properties.Resources.ko_ninja_js);
            this.AddScriptElement(Properties.Resources.statblockHelpers_js);
            this.AddScriptElement(Properties.Resources.bindingHandlers_js);
        }
Example #30
0
        static Task <bool> WaitForPageLoadAsync(WebBrowser browser, CancellationToken token)
        {
            var tcs = new TaskCompletionSource <bool>();

            token.Register(() => tcs.TrySetCanceled());
            WebBrowserDocumentCompletedEventHandler handler = null;

            handler = (s, e) =>
            {
                if (e.Url.AbsolutePath == "blank")
                {
                    return;
                }

                browser.DocumentCompleted -= handler;
                tcs.TrySetResult(true);
            };
            browser.DocumentCompleted += handler;
            return(tcs.Task);
        }
Example #31
0
 public void setCompletedListener(WebBrowserDocumentCompletedEventHandler handler)
 {
     myBrowser.DocumentCompleted += handler;
 }
Example #32
0
 public virtual void init()
 {
     RequestContext = new Dictionary<string, object>();
     Outputs = new Dictionary<string, object>();
     if (MonitorTimings)
     {
         completedEventHandlerForTiming = new WebBrowserDocumentCompletedEventHandler(this.pageLoadedForMonitoring);
         WebBrowser.DocumentCompleted += completedEventHandlerForTiming;
         AccessTimes = new Stack<AccessTiming>();
     }
 }
Example #33
0
 /// <summary>
 /// Removes documentCompletedHandler from browser.DocumentCompleted, replaces it with the supplied function, and then adds it back.
 /// </summary>
 /// <param name="function"></param>
 private void resetdocumentCompletedHandler(WebBrowserDocumentCompletedEventHandler function)
 {
     browser.DocumentCompleted -= documentCompletedHandler;
     documentCompletedHandler = function;
     browser.DocumentCompleted += documentCompletedHandler;
 }
Example #34
0
 public virtual void doActions(List<WebAction> actions)
 {
     completedEventHandler = new WebBrowserDocumentCompletedEventHandler(this.pageLoaded);
     WebBrowser.DocumentCompleted += completedEventHandler;
     activeActions = new Queue<WebAction>(actions);
     doNextAction();
 }
Example #35
0
 public virtual void doActions(List<WebAction> actions)
 {
     completedEventHandler = new WebBrowserDocumentCompletedEventHandler(this.pageLoaded);
     WebBrowser.DocumentCompleted += completedEventHandler;
     Queue<WebAction> activeActions = new Queue<WebAction>(actions);
     while (0 < activeActions.Count)
     {
         activeAction = activeActions.Dequeue();
         if (activeAction.canDoAction(this))
         {
             if (activeAction.shouldWaitAction(this))
             {
                 trigger.Reset();
                 WaitHandle.WaitAny(waitHandles);
             }
             activeAction.doAction(this);
             if (activeAction.isWaitForEvent())
             {
                 trigger.Reset();
                 WaitHandle.WaitAny(waitHandles);
             }
         }
     }
     completedActions();
 }
Example #36
0
 public CompletionClosure()
 {
     done = false;
     Handler = new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
 }
Example #37
0
        private void StopListeningAndAddCommonHtmlElements(WebBrowserDocumentCompletedEventHandler completedHandler)
        {
            // ordering of the following is IMPORTANT
            // stop listening
            this.AllowNavigation = false;
            this.DocumentCompleted -= completedHandler;

            // load our css in
            this.AddStyleSheet(Properties.Resources.statblock_css);

            // load our javascript in
            this.AddScriptElement(Properties.Resources.modernizr_2_6_2_js);
            this.AddScriptElement(Properties.Resources.underscore_js);
            this.AddScriptElement(Properties.Resources.knockout_3_0_0_debug_js);
            this.AddScriptElement(Properties.Resources.knockout_StringInterpolatingBindingProvider_js);
            this.AddScriptElement(Properties.Resources.ko_ninja_js);
            this.AddScriptElement(Properties.Resources.statblockHelpers_js);
            this.AddScriptElement(Properties.Resources.bindingHandlers_js);
        }