Home > Blockchain >  CefSharp Search Engine Implamentation
CefSharp Search Engine Implamentation

Time:01-02

I am working on a cefsharp based browser and i am trying to implement a search engine into the browser, but the code I have tried docent work, it doesn't really have any errors but when i star the project and type something i the text field nothing happens and it dosent load the search engine i entered into the code, the only time the textbox loads anything is when a url is typed.

This is the code used in the browser that docent work

    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);
        }
    }

i have also tried

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

CodePudding user response:

We have here really few Information on how your code works. But what I notice is that you use WebUtility.HtmlEncode for the search query. WebUtility has also a WebUtility.UrlEncode Method, that how I understand your question makes more sense it the context. This is the documentation for the method: https://learn.microsoft.com/de-de/dotnet/api/system.net.webutility.urlencode

CodePudding user response:

The Url you are generating is invalid. You need to use Uri.EscapeDataString to convert the url param into a string that can be appended to a url.

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

    chromiumWebBrowser.LoadUrl(searchUrl);
}

nothing happens and it dosent load the search engine

You need to subscribe to the LoadError event to get actual error messages. It's up to you to display errors to the user. The following is a basic example:

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);
}

For testing purposes you can also copy and paste the searchUrl string you've generated and try loading it in Chrome to see what happens, you should also get an error.

  • Related