privateclassLocalContentWebViewClient(privatevalassetLoader:WebViewAssetLoader):WebViewClientCompat(){@RequiresApi(21)overridefunshouldInterceptRequest(view:WebView,request:WebResourceRequest):WebResourceResponse? {returnassetLoader.shouldInterceptRequest(request.url)}// To support API < 21.overridefunshouldInterceptRequest(view:WebView,url:String):WebResourceResponse? {returnassetLoader.shouldInterceptRequest(Uri.parse(url))}}
Java
privatestaticclassLocalContentWebViewClientextendsWebViewClientCompat{privatefinalWebViewAssetLoadermAssetLoader;LocalContentWebViewClient(WebViewAssetLoaderassetLoader){mAssetLoader=assetLoader;}@Override@RequiresApi(21)publicWebResourceResponseshouldInterceptRequest(WebViewview,WebResourceRequestrequest){returnmAssetLoader.shouldInterceptRequest(request.getUrl());}@Override@SuppressWarnings("deprecation")// To support API < 21.publicWebResourceResponseshouldInterceptRequest(WebViewview,Stringurl){returnmAssetLoader.shouldInterceptRequest(Uri.parse(url));}}
valassetLoader=WebViewAssetLoader.Builder().setDomain("example.com")// Replace this with your website's domain..addPathHandler("/assets/",AssetsPathHandler(this)).build()webView.webViewClient=LocalContentWebViewClient(assetLoader)valinAppHtmlUrl="https://example.com/assets/index.html"webView.loadUrl(inAppHtmlUrl)valwebsiteUrl="https://example.com/website/data.json"// JavaScript code to fetch() content from the same origin.valjsCode="fetch('$websiteUrl')"+".then(resp => resp.json())"+".then(data => console.log(data));"webView.evaluateJavascript(jsCode,null)
Java
finalWebViewAssetLoaderassetLoader=newWebViewAssetLoader.Builder().setDomain("example.com")// Replace this with your website's domain.
.addPathHandler("/assets/",newAssetsPathHandler(this)).build();mWebView.setWebViewClient(newLocalContentWebViewClient(assetLoader));StringinAppHtmlUrl="https://example.com/assets/index.html";mWebView.loadUrl(inAppHtmlUrl);StringwebsiteUrl="https://example.com/website/data.json";// JavaScript code to fetch() content from the same origin.StringjsCode="fetch('"+websiteUrl+"')"+".then(resp => resp.json())"+".then(data => console.log(data));";mWebView.evaluateJavascript(jsCode,null);