Search code examples
androidwebviewandroid-edittextsearchviewsearchbar

How to search on a website's search bar in WebView by using EditText?


I have an EditText and a WebView. The WebView loads Amazon website when initialized. When I enter a query in EditText I want the Amazon website search for the query(search on the website's search bar). Any help is highly appreciated. Here is my code

webView = v.findViewById(R.id.webview);
    url = "https://amazon.com";
    webView.setWebViewClient(new WebViewClient(){

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                view.loadUrl(String.valueOf(request.getUrl()));
            }
            return true;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed(); // Ignore SSL certificate errors
        }
    });

    webView.getSettings().setLoadsImagesAutomatically(true);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    webView.loadUrl(url);

Solution

  • You could just navigate the WebView to the search url from Amazon:

    https://www.amazon.com/s/?field-keywords=search keyword(s)

    final String searchURL = "https://www.amazon.com/s/?field-keywords=";
    String keywords = "something";
    view.loadUrl(searchURL + keywords);
    

    Maybe you need to convert the keywoards to an URL conform format, especially when containing special chars.