```html
<!-- index.html content -->
<html>
<head>
<!-- Tip: Use relative URLs when referring to other in-app content to give
your app code the flexibility to change the scheme or domain as
necessary. -->
<link rel="stylesheet" href="/assets/stylesheet.css">
</head>
<body>
<p>This file is loaded from in-app content.</p>
<p><img src="/res/drawable/android_robot.png" alt="Android robot" width="100"></p>
</body>
</html>
```
```css
<!-- stylesheet.css content -->
body {
background-color: lightblue;
}
```
final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
.addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(this)).addPathHandler("/res/", new WebViewAssetLoader.ResourcesPathHandler(this))
.build();
mWebView.setWebViewClient(new LocalContentWebViewClient(assetLoader));
val assetLoader = WebViewAssetLoader.Builder()
.setDomain("example.com") // Replace this with your website's domain.
.addPathHandler("/assets/", AssetsPathHandler(this))
.build()
webView.webViewClient = LocalContentWebViewClient(assetLoader)
val inAppHtmlUrl = "https://example.com/assets/index.html"
webView.loadUrl(inAppHtmlUrl)
val websiteUrl = "https://example.com/website/data.json"
// JavaScript code to fetch() content from the same origin.
val jsCode = "fetch('$websiteUrl')" +
".then(resp => resp.json())" +
".then(data => console.log(data));"
webView.evaluateJavascript(jsCode, null)
Java
final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
.setDomain("example.com") // Replace this with your website's domain.
.addPathHandler("/assets/", new AssetsPathHandler(this))
.build();
mWebView.setWebViewClient(new LocalContentWebViewClient(assetLoader));
String inAppHtmlUrl = "https://example.com/assets/index.html";
mWebView.loadUrl(inAppHtmlUrl);
String websiteUrl = "https://example.com/website/data.json";
// JavaScript code to fetch() content from the same origin.
String jsCode = "fetch('" + websiteUrl + "')" +
".then(resp => resp.json())" +
".then(data => console.log(data));";
mWebView.evaluateJavascript(jsCode, null);
เมื่อแอปของคุณต้องการโหลดหน้า HTML เท่านั้นและไม่จําเป็นต้องสกัดกั้น
ทรัพยากรย่อย ให้พิจารณาใช้
loadDataWithBaseURL()
ซึ่งไม่ต้องใช้ชิ้นงานแอป คุณสามารถใช้งานบัญชีได้ดังที่แสดงในรหัสต่อไปนี้
ตัวอย่าง:
Kotlin
val html = "<html><body><p>Hello world</p></body></html>"
val baseUrl = "https://example.com/"
webView.loadDataWithBaseURL(baseUrl, html, "text/html", null, baseUrl)