Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách bật chế độ mixed content cho WebView Android

Giới thiệu

Hướng dẫn này trình bày cách bật hỗ trợ mixed content (nội dung hỗn hợp HTTP/HTTPS) trong Android WebView. Từ Android 5.0 (Lollipop), WebView mặc định chặn nội dung HTTP trên trang HTTPS vì lý do bảo mật.

Các bước thực hiện

Bước 1: Tạo dự án mới

Tạo dự án Android Studio mới: File → New Project.

Bước 2: Layout activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Bước 3: MainActivity.java

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.ProgressDialog;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Đang tải dữ liệu...");
        progressDialog.setCancelable(false);

        WebView webView = findViewById(R.id.web_view);
        webView.requestFocus();
        
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        
        // QUAN TRỌNG: Bật mixed content mode
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
            // Các tùy chọn khác:
            // MIXED_CONTENT_ALWAYS_ALLOW - Cho phép tất cả (không khuyến khích)
            // MIXED_CONTENT_NEVER_ALLOW - Chặn hoàn toàn (mặc định từ API 21+)
        }

        webView.loadUrl("https://www.tutorialspoint.com/");

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

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100) {
                    progressDialog.show();
                }
                if (newProgress == 100) {
                    progressDialog.dismiss();
                }
            }
        });
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Giải thích các chế độ Mixed Content

Hằng sốMô tảKhuyến nghị
MIXED_CONTENT_COMPATIBILITY_MODECho phép nội dung HTTP từ các nguồn đã truy cập trước đó (mặc định API 21-25)✅ An toàn, tương thích
MIXED_CONTENT_ALWAYS_ALLOWCho phép tất cả nội dung HTTP trên HTTPS⚠️ Chỉ dùng test, không production
MIXED_CONTENT_NEVER_ALLOWChặn hoàn toàn nội dung HTTP trên HTTPS (mặc định API 26+)✅ An toàn nhất

Lưu ý bảo mật quan trọng

  • Việc bật mixed content làm giảm bảo mật - kẻ tấn công có thể chèn script HTTP vào trang HTTPS.
  • Chỉ sử dụng MIXED_CONTENT_ALWAYS_ALLOW trong môi trường phát triển/test.
  • Khuyến khích di chuyển tất cả tài nguyên sang HTTPS thay vì bật mixed content.
  • Từ Android 8.0 (API 26), mặc định là MIXED_CONTENT_NEVER_ALLOW.