Detecting 404 errors in WebView typically involves monitoring the loading state of content within the WebView to determine if a 404 (page not found) error has occurred. Different platforms and programming languages employ distinct approaches for this functionality. Here are examples for two common platforms:
Android WebView (Java/Kotlin)
In Android, you can detect 404 errors by overriding the onReceivedError() method of the WebViewClient class. For example:
javaWebView webView = findViewById(R.id.webview); webView.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (error.getErrorCode() == 404) { // Handle 404 error here Toast.makeText(MyActivity.this, "Page not found (404)", Toast.LENGTH_LONG).show(); } } } @Override public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) { super.onReceivedHttpError(view, request, errorResponse); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (errorResponse.getStatusCode() == 404) { // Handle 404 error here Toast.makeText(MyActivity.this, "Page not found (HTTP 404)", Toast.LENGTH_LONG).show(); } } } }); webView.loadUrl("http://www.example.com");
Note that the onReceivedError() method captures all errors occurring during the request, including 404 errors. The onReceivedHttpError() method specifically targets HTTP error codes.
iOS WebView (Swift)
In iOS, when using WKWebView, you can detect errors by implementing the webView(_:didFailProvisionalNavigation:withError:) and webView(_:didFail:withError:) methods of the WKNavigationDelegate protocol.
swiftimport WebKit class ViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() webView = WKWebView(frame: view.bounds) webView.navigationDelegate = self view.addSubview(webView) if let url = URL(string: "http://www.example.com") { let request = URLRequest(url: url) webView.load(request) } } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { if let errorCode = (error as NSError).code, errorCode == 404 { // Handle 404 error print("Page not found (404)") } } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { if let errorCode = (error as NSError).code, errorCode == 404 { // Handle 404 error print("Page not found (404)") } } }
In this example, if a 404 error occurs, it is captured and can be handled within these delegate methods.
These code snippets illustrate how to detect 404 errors in WebView across different platforms. In practice, you may also need to handle other error types and provide users with appropriate feedback or fallback options.