簡體   English   中英

如何從Webbrowser C#返回javascript函數值

[英]how to return javascript function value from webbrowser c#

嗨,Awesomium瀏覽器向JavaScript提供了帶有result方法的execute以返回如下值:

private const String JS_FAVICON = "(function(){links = document.getElementsByTagName('link'); wHref=window.location.protocol + '//' + window.location.hostname + '/favicon.ico'; for(i=0; i<links.length; i++){s=links[i].rel; if(s.indexOf('icon') != -1){ wHref = links[i].href }; }; return wHref; })();";
string val = webControl.ExecuteJavascriptWithResult(JS_FAVICON); 

但是我需要使用c#內置瀏覽器執行此操作,我認為有方法“ webBrowser1.Document.InvokeScript”不確定如何使用它。

編輯...這是Awesomium瀏覽器如何返回值:

private void Awesomium_Windows_Forms_WebControl_DocumentReady(object  sender, UrlEventArgs e)
    {
        // DOM is ready. We can start looking for a favicon.
        //UpdateFavicon();
    }


 private void UpdateFavicon()
    {
        // Execute some simple javascript that will search for a favicon.
        string val = webControl.ExecuteJavascriptWithResult(JS_FAVICON);

        // Check for any errors.
        if (webControl.GetLastError() != Error.None)
            return;

        // Check if we got a valid response.
        if (String.IsNullOrEmpty(val) || !Uri.IsWellFormedUriString(val, UriKind.Absolute))
            return;

        // We do not need to perform the download of the favicon synchronously.
        // May be a full icon set (thus big).
        Task.Factory.StartNew<Icon>(GetFavicon, val).ContinueWith(t =>
        {
            // If the download completed successfully, set the new favicon.
            // This post-completion procedure is executed synchronously.

            if (t.Exception != null)
                return;

            if (t.Result != null)
                this.Icon = t.Result;

            if (this.DockPanel != null)
                this.DockPanel.Refresh();
        },
        TaskScheduler.FromCurrentSynchronizationContext());
    }

    private static Icon GetFavicon(Object href)
    {
        using (WebClient client = new WebClient())
        {
            Byte[] data = client.DownloadData(href.ToString());

            if ((data == null) || (data.Length <= 0))
                return null;

            using (MemoryStream ms = new MemoryStream(data))
            {
                try
                {
                    return new Icon(ms, 16, 16);
                }
                catch (ArgumentException)
                {
                    // May not be an icon file.
                    using (Bitmap b = new Bitmap(ms))
                        return Icon.FromHandle(b.GetHicon());
                }
            }
        }
    }

這就是我使用WinForm瀏覽器的方法:

 private void webBrowser1_DocumentCompleted(object sender,   WebBrowserDocumentCompletedEventArgs e)
 {
        UpdateFavicon();
 }
 private void UpdateFavicon()
 {
   var obj = webBrowser1.Document.InvokeScript("_X_");
   string val = webBrowser1.DocumentText = "<script> function _X_(){return " + JS_FAVICON + ";} </script>"; 
 }

正如@JohnSmith所說,這是不可能的

一個簡單的技巧,您可以從javascript獲取返回值

string JS_FAVICON = "(function(){links = document.getElementsByTagName('link'); wHref=window.location.protocol + '//' + window.location.hostname + '/favicon.ico'; for(i=0; i<links.length; i++){s=links[i].rel; if(s.indexOf('icon') != -1){ wHref = links[i].href }; }; return wHref; })();";

webBrowser1.DocumentCompleted += (s, e) =>
{
    var obj = webBrowser1.Document.InvokeScript("_X_");
    //obj will be about:///favicon.ico
    //write your code that handles the return value here
};

string val = webBrowser1.DocumentText = "<script> function _X_(){return " + JS_FAVICON + ";} </script>";

但是,由於我們可以在DocumentCompleted處理程序中獲取該值,因此您不能直接從調用方法中返回它。 如果您可以用這種方法繼續工作,那就沒問題了。 如果沒有,那么它需要更多技巧來完成它。 讓我知道...

更新

這是完整的工作代碼,只需在表單中的某處調用TestJavascript

async void TestJavascript()
{
    string JS_FAVICON = "(function(){links = document.getElementsByTagName('link'); wHref=window.location.protocol + '//' + window.location.hostname + '/favicon.ico'; for(i=0; i<links.length; i++){s=links[i].rel; if(s.indexOf('icon') != -1){ wHref = links[i].href }; }; return wHref; })();";

    var retval = await Execute(webBrowser1, JS_FAVICON);
    MessageBox.Show(retval.ToString());
}

Task<object> Execute(WebBrowser wb,  string anonJsFunc)
{
    var tcs = new TaskCompletionSource<object>();
    WebBrowserDocumentCompletedEventHandler documentCompleted = null;
    documentCompleted = (s, e) =>
    {
        var obj = wb.Document.InvokeScript("_X_");
        tcs.TrySetResult(obj);
        wb.DocumentCompleted -= documentCompleted; //detach
    };

    wb.DocumentCompleted += documentCompleted; //attach
    string val = wb.DocumentText = "<script> function _X_(){return " +
                                    anonJsFunc +
                                    ";} </script>";

    return tcs.Task;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM