簡體   English   中英

CefSharp 搜索引擎實現

[英]CefSharp Search Engine Implamentation

我正在使用基於 cefsharp 的瀏覽器,我正在嘗試在瀏覽器中實現一個搜索引擎,但是我嘗試過的代碼可以正常工作,它實際上沒有任何錯誤,但是當我為項目加注星標並在文本中輸入一些內容時字段沒有任何反應,它不會加載我在代碼中輸入的搜索引擎,唯一一次文本框加載任何內容是在鍵入 url 時。

這是 docent 工作的瀏覽器中使用的代碼

    private void LoadUrl(string url)
    {
        if (Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
        {
            WebUI.Load(url);
        }
        else
        {
            var searchUrl = "https://www.google.com/search?q=" + WebUtility.HtmlEncode(url);

            WebUI.Load(searchUrl);
        }
    }

我也試過

        void LoadURl(String url)
        {
            if (url.StartsWith("http"))
            {
                WebUI.Load(url);
            }
            else
            {
            WebUI.Load(url);
            }
        }

我也被建議嘗試

    private void LoadUrl(string url)
    {
        if (Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
        {
            WebUI.LoadUrl(url);
        }
        else
        {
            var searchUrl = "https://www.google.com/search?q=" + Uri.EscapeDataString(url);

            WebUI.LoadUrl(searchUrl);
        }
    }

我們這里幾乎沒有關於您的代碼如何工作的信息。 但我注意到您使用WebUtility.HtmlEncode進行搜索查詢。 WebUtility還有一個WebUtility.UrlEncode方法,我理解你的問題的方式在上下文中更有意義。 這是該方法的文檔: https://learn.microsoft.com/de-de/do.net/api/system.net.webutility.urlencode

您生成的 Url 無效。 您需要使用Uri.EscapeDataString將 url 參數轉換為可以附加到 url 的字符串。

// For this example we check if a well formed absolute Uri was provided
// and load that Url, all others will be loaded using the search engine
// e.g. https://github.com will load directly, attempting to load
// github.com will load the search engine with github.com as the query.
// 
if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
    chromiumWebBrowser.LoadUrl(url);
}
else
{
    var searchUrl = "https://www.google.com/search?q=" + Uri.EscapeDataString(url);

    chromiumWebBrowser.LoadUrl(searchUrl);
}

沒有任何反應,它不會加載搜索引擎

您需要訂閱LoadError事件以獲取實際的錯誤消息。 向用戶顯示錯誤取決於您。 以下是一個基本示例:

chromiumWebBrowser.LoadError += OnChromiumWebBrowserLoadError;

private void OnChromiumWebBrowserLoadError(object sender, LoadErrorEventArgs e)
{
    //Actions that trigger a download will raise an aborted error.
    //Aborted is generally safe to ignore
    if (e.ErrorCode == CefErrorCode.Aborted)
    {
        return;
    }

    var errorHtml = string.Format("<html><body><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>",
                                      e.FailedUrl, e.ErrorText, e.ErrorCode);

    _ = e.Browser.SetMainFrameDocumentContentAsync(errorHtml);
}

出於測試目的,您還可以復制並粘貼您生成的searchUrl字符串,然后嘗試將其加載到Chrome中以查看會發生什么,您也應該會收到錯誤消息。

暫無
暫無

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

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