การล้างประวัติ (History) ของ WebView ใน Android
ตัวอย่างนี้สาธิตวิธีใช้ WebView.clearHistory() เพื่อล้างประวัติการนำทาง (Navigation History) ของ WebView ป้องกันผู้ใช้กด Back กลับไปหน้าเก่าได้ และปรับปรุงความเป็นส่วนตัว
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
สร้างโปรเจกต์ Android ใหม่ใน Android Studio
ขั้นตอนที่ 2: เพิ่ม Permission ใน 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>
ขั้นตอนที่ 3: ออกแบบ Layout (res/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"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
ขั้นตอนที่ 4: MainActivity.java
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ProgressDialog progressDialog;
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("กำลังโหลด...");
progressDialog.setCancelable(false);
webView = findViewById(R.id.webView);
webView.requestFocus();
// การตั้งค่า WebView
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true); // เปิด JavaScript
settings.setDomStorageEnabled(true); // LocalStorage/SessionStorage
settings.setDatabaseEnabled(true); // Web SQL Database
settings.setCacheMode(WebSettings.LOAD_DEFAULT); // ใช้ Cache ตามปกติ
settings.setLoadWithOverviewMode(true); // Zoom to fit
settings.setUseWideViewPort(true); // Wide Viewport
settings.setBuiltInZoomControls(true); // Zoom Controls
settings.setDisplayZoomControls(false); // ซ่อน UI Zoom
settings.setSupportZoom(true); // รองรับ Zoom
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
// จุดสำคัญ: ล้างประวัติการนำทาง
webView.clearHistory();
// ตั้งค่า WebViewClient เพื่อจัดการ Navigation ภายใน App
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
// WebChromeClient สำหรับ Progress และ JavaScript Dialogs
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress < 100 && !progressDialog.isShowing()) {
progressDialog.show();
} else if (newProgress == 100 && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
public boolean onJsAlert(WebView view, String url, String message, android.webkit.JsResult result) {
// Handle JavaScript alert()
return super.onJsAlert(view, url, message, result);
}
});
// โหลดเว็บไซต์
webView.loadUrl("https://mylocation.org/");
}
@Override
public void onBackPressed() {
// จัดการปุ่ม Back: ถ้ามี History ให้ย้อนกลับใน WebView, ไม่เช่นนั้นปิด App
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Cleanup WebView
webView.clearHistory();
webView.clearCache(true);
webView.clearFormData();
webView.destroy();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
คำอธิบาย WebView History Methods
1. clearHistory() - ล้างประวัติการนำทาง
webView.clearHistory();
- ล้าง Back/Forward History Stack ทั้งหมด
- หลังเรียก:
canGoBack()จะคืนค่าfalse - ไม่ล้าง: Cache, Cookies, Form Data, LocalStorage
- ใช้เมื่อ: เริ่ม Session ใหม่, Logout, Privacy-sensitive pages
2. clearCache(boolean includeDiskFiles)
webView.clearCache(true); // ล้าง Memory + Disk Cache webView.clearCache(false); // ล้าง Memory Cache เท่านั้น
3. clearFormData() - ล้างข้อมูลฟอร์ม
webView.clearFormData();
- ล้าง Autofill Data, Saved Passwords, Form Inputs
4. clearSslPreferences() - ล้าง SSL Preferences
webView.clearSslPreferences();
WebView History Navigation
// ตรวจสอบว่าย้อนกลับได้ไหม
if (webView.canGoBack()) {
webView.goBack(); // ย้อนกลับ 1 หน้า
}
// ตรวจสอบว่าไปข้างหน้าได้ไหม
if (webView.canGoForward()) {
webView.goForward(); // ไปข้างหน้า 1 หน้า
}
// ย้อนกลับหลายขั้น
webView.goBackOrForward(-3); // ย้อน 3 หน้า
การจัดการ Cookies (เพิ่มเติม)
import android.webkit.CookieManager; // ล้าง Cookies ทั้งหมด CookieManager.getInstance().removeAllCookies(null); // ล้าง Cookies สำหรับ URL เฉพาะ CookieManager.getInstance().removeSessionCookies(null); // Flush to persistent storage CookieManager.getInstance().flush();
Best Practices สำหรับ WebView
1. Security Settings
WebSettings settings = webView.getSettings(); settings.setAllowFileAccess(false); // ไม่อนุญาต File Access settings.setAllowContentAccess(false); // ไม่อนุญาต Content Provider Access settings.setAllowFileAccessFromFileURLs(false); settings.setAllowUniversalAccessFromFileURLs(false); settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW); // HTTPS Only
2. Performance Settings
settings.setRenderPriority(WebSettings.RenderPriority.HIGH); settings.setEnableSmoothTransition(true);
3. Lifecycle Management
@Override
protected void onPause() {
super.onPause();
webView.onPause(); // หยุด JavaScript, Animations
}
@Override
protected void onResume() {
super.onResume();
webView.onResume(); // Resume JavaScript, Animations
}
@Override
protected void onDestroy() {
webView.loadUrl("about:blank"); // หยุด Loading
webView.clearHistory();
webView.clearCache(true);
webView.clearFormData();
webView.destroy(); // สำคัญ: ปล่อย Resources
super.onDestroy();
}
กรณีการใช้งานจริง
- Login/Logout: clearHistory() + clearFormData() + removeAllCookies() ตอน Logout
- Payment Flow: clearHistory() หลังชำระเงินเสร็จ ป้องกันกด Back กลับหน้าจ่ายเงิน
- Private Mode: ไม่เก็บ History, Cache, Cookies ตลอด Session
- Deep Linking: clearHistory() เมื่อเปิดจาก Deep Link เพื่อป้องกัน Back กลับ App เดิม
- Kiosk Mode: clearHistory() ทุกครั้งที่เริ่ม Session ใหม่
ข้อควรระวัง
- clearHistory() ไม่ล้าง Cache/Cookies - ต้องเรียกแยกกัน
- WebView.destroy() ต้องเรียกใน onDestroy() ป้องกัน Memory Leak
- JavaScript Enabled = Security Risk - ใช้เฉพาะ Trusted Content
- Mixed Content (HTTP ใน HTTPS) - ตั้งค่า MIXED_CONTENT_NEVER_ALLOW
- Target API 28+ (Android 9) ต้องใช้ Network Security Config สำหรับ Cleartext Traffic
Network Security Config (res/xml/network_security_config.xml)
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="false">
<domain includeSubdomains="true">mylocation.org</domain>
</domain-config>
</network-security-config>
เพิ่มใน Manifest: android:networkSecurityConfig="@xml/network_security_config"