You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Android HTML应用开发:如何使用WebViewAssetLoader加载多个JS文件?

Fixing CORS Issues for Local JS Files in Android WebView: A Complete WebViewAssetLoader Guide

Hey there! I totally get the frustration when official docs drop code snippets without context—especially when you're jumping into Android Java for the first time as an experienced dev. Let's break down exactly where to put that LocalContentWebViewClient code and how to wire everything up to fix your CORS issues with multiple JS files.

Step 1: Nest the LocalContentWebViewClient Class Inside MainActivity

The LocalContentWebViewClient is meant to be a static inner class of your MainActivity. This keeps related code organized and lets it access the context it needs. Here's how your updated MainActivity.java will look, with the client class integrated:

package com.example.myappname;

import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClientCompat;
import androidx.webkit.WebViewAssetLoader;
import androidx.webkit.WebViewAssetLoader.AssetsPathHandler;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.RequiresApi;

public class MainActivity extends AppCompatActivity {

    // Add the static inner class HERE, inside MainActivity's curly braces
    private static class LocalContentWebViewClient extends WebViewClientCompat {
        private final WebViewAssetLoader mAssetLoader;

        LocalContentWebViewClient(WebViewAssetLoader assetLoader) {
            mAssetLoader = assetLoader;
        }

        @Override
        @RequiresApi(21)
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            return mAssetLoader.shouldInterceptRequest(request.getUrl());
        }

        @Override
        @SuppressWarnings("deprecation") // Supports devices running API < 21
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            return mAssetLoader.shouldInterceptRequest(Uri.parse(url));
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = findViewById(R.id.webview);

        // 1. Initialize WebViewAssetLoader to map virtual URLs to local assets
        WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
                .addPathHandler("/assets/", new AssetsPathHandler(this))
                .build();

        // 2. Attach your custom WebViewClient to the WebView
        webView.setWebViewClient(new LocalContentWebViewClient(assetLoader));

        // 3. Configure WebView settings (keep your existing settings + add DOM storage if needed)
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true); // Enable if your JS uses localStorage/sessionStorage
        webView.setLayerType(WebView.LAYER_TYPE_HARDWARE, null);

        // 4. Load your HTML using the virtual HTTPS domain (NO MORE file:// URLs!)
        webView.loadUrl("https://appassets.androidplatform.net/index.html");
    }
}

Step 2: Add the Required WebView Dependency

WebViewAssetLoader is part of the AndroidX WebKit library, so you need to add it to your project's dependencies. Open your Module-level build.gradle (usually app/build.gradle) and add this line to the dependencies block:

dependencies {
    // Keep your existing dependencies...
    implementation 'androidx.webkit:webkit:1.6.0' // Use the latest version recommended by Android Studio
}

Key Changes Explained

  • Static Inner Class Placement: The LocalContentWebViewClient lives inside MainActivity because it's tightly coupled to the WebView setup for this activity. Static ensures it doesn't hold an unnecessary reference to the activity instance.
  • WebViewAssetLoader Setup: The builder maps the virtual path /assets/ to your project's src/main/assets directory. If your HTML/JS is in a subfolder (e.g., assets/web/), update the path handler to /web/ and adjust the load URL to https://appassets.androidplatform.net/web/index.html.
  • HTTPS Virtual Domain: Replacing file:///android_asset/ with https://appassets.androidplatform.net/ fixes CORS because all your local resources now load from the same "origin", complying with the same-origin policy.

Verify Your Asset Structure

Make sure your local files are in the correct assets directory:

src/
└── main/
    ├── assets/
    │   ├── index.html
    │   ├── style.css
    │   ├── main.js
    │   └── utils.js
    └── java/
        └── com/example/myappname/
            └── MainActivity.java

Once you make these changes, run your app—your multiple JS files should load without CORS errors, and you'll be following Android's recommended secure pattern for loading local web content.

内容的提问来源于stack exchange,提问作者h4tt3n

火山引擎 最新活动