คุณจะแก้ไขข้อผิดพลาดการเปลี่ยนเส้นทาง WebView บน Android และ iOS ได้อย่างไร? ระบุว่าความล้มเหลวนั้นเกี่ยวข้องกับการนำทางผ่าน HTTPS มาตรฐาน, custom URL scheme, intent:// URI ของ Android, หรือคำขอเปิดหน้าต่างใหม่ จากนั้นตรวจสอบการนำทางผ่าน Chrome DevTools หรือ Safari Web Inspector และติดตาม native delegate ที่เกี่ยวข้อง (shouldOverrideUrlLoading, onCreateWindow, decidePolicyForNavigationAction, หรือ createWebViewWith) ตรวจสอบการแปลงแอปเป้าหมาย, URI allowlists, นโยบายเฟรมและการโต้ตอบของผู้ใช้ รวมถึงเส้นทางสำรอง (fallback routing) เพื่อแยกข้อผิดพลาดระดับคอนเทนเนอร์ออกจากความล้มเหลวในการส่งต่อของระบบปฏิบัติการ
ข้อผิดพลาดการเปลี่ยนเส้นทาง WebView จะเกิดขึ้นเมื่อ Android Chromium WebView หรือ iOS WebKit WKWebView ที่ฝังอยู่ไม่สามารถส่งคำไปยังปลายทางที่ต้องการได้ สาเหตุทั่วไปได้แก่ custom URL schemes ที่ไม่รองรับ, คำขอ
target="_blank"ที่ไม่มีการจัดการ, การประกาศการมองเห็นแพ็กเกจที่หายไป และการเปลี่ยนเส้นทางสำรองที่ถูกปฏิเสธหรือเกิดวงวนซ้ำ
ทำไมคอนเทนเนอร์ Android WebView และ iOS WKWebView ที่ฝังอยู่จึงทิ้งการเปลี่ยนเส้นทาง

เมื่อทำการดีบักความล้มเหลวในการเปลี่ยนเส้นทาง ทีมวิศวกรจะต้องแยก พฤติกรรมของเอนจิ้น WebView (วิธีที่ Chromium หรือ WebKit แยกวิเคราะห์ URL, เฟรมเป้าหมาย และป๊อปอัปอีเวนต์) ออกจาก นโยบายของแอปพลิเคชันโฮสต์ (วิธีที่ WebViewClient, WebChromeClient, WKNavigationDelegate, หรือ WKUIDelegate ที่แอปพลิเคชันจัดเตรียมไว้ประเมินประเภทการโต้ตอบของผู้ใช้, allowlists และการส่งต่อแอปภายนอก) เบราว์เซอร์ทั่วไปจะมีระบบจัดการ URI และตัวจัดการการส่งต่อลิงก์ในตัว ในขณะที่ android.webkit.WebView และ WKWebView ของ Apple เป็นคอมโพเนนต์การเรนเดอร์แบบฝังที่คาดหวังการตอบสนองของเครือข่าย http:// หรือ https:// มาตรฐานตามค่าเริ่มต้น
เมื่อหน้าเว็บทริกเกอร์ custom scheme (เช่น myapp://product/42) หรือลิงก์ intent:// ของ Android โดยไม่มีการเขียนทับ delegate ที่ใช้งานอยู่ พฤติกรรมเริ่มต้นของคอนเทนเนอร์จะแตกต่างกันไปตามแพลตฟอร์ม:
- Android Chromium WebView: ตามข้อกำหนดของ Android
WebViewClientหากไม่มีการกำหนด customWebViewClient, WebView อาจขอให้ Activity Manager แปลง URL ผ่านตัวจัดการระบบที่มีอยู่ เมื่อมีการกำหนด customWebViewClientและshouldOverrideUrlLoadingส่งค่าfalseสำหรับ custom scheme ที่ไม่รองรับ, WebView จะยังคงโหลดภายใน Chromium ต่อไปและแสดงผลเป็นnet::ERR_UNKNOWN_URL_SCHEME - iOS WebKit WKWebView: WebKit จะปฏิเสธ non-HTTP schemes ภายในและยกเลิกการนำทางเว้นแต่
WKNavigationDelegateของโฮสต์จะดักจับคำขอนั้นและส่งต่อไปยังUIApplicationซึ่งมักจะล้มเหลวแบบเงียบ ๆ หรือทริกเกอร์NSURLErrorUnsupportedURL
โปรดสังเกตด้วยว่าฟีเจอร์ Promoting Apps with Smart App Banners ของ Apple เป็นฟีเจอร์สนับสนุนของ Safari ที่ออกแบบมาสำหรับการท่องเว็บ Safari ทั่วไป มากกว่าที่จะเป็น API การนำทางของ WKWebView แบบฝัง และควรได้รับการประเมินแยกต่างหากจากการเปลี่ยนเส้นทาง custom URL scheme ภายในแอป
สรุปสั้นๆ
- แยกพฤติกรรมของเอนจิ้นออกจากนโยบายโฮสต์: แยกแยะว่าการนำทางล้มเหลวภายในเอนจิ้นเว็บ (Chromium/WebKit), ภายในส่วนการเขียนทับ native delegate, หรือที่ขอบเขตการแก้ไขแพ็กเกจของ OS
- ตรวจสอบการเปลี่ยนเส้นทางแบบสดก่อนเขียนโค้ด: ใช้ Chrome DevTools (
chrome://inspect) และ Safari Web Inspector (isInspectable = true) เพื่อบันทึก 3xx redirect chains, สถานะtargetFrameและแฟล็กท่าทางสัมผัส - บังคับใช้การตรวจสอบ URI และ Intent ที่เหมาะสมกับแพลตฟอร์ม: บน Android ให้ผูก custom schemes และเป้าหมาย
intent://แบบ 1 ต่อ 1 กับแพ็กเกจที่ตรวจสอบแล้วผ่านIntentSanitizerโดยไม่มีแฟล็กงานที่จัดเตรียมโดยหน้าเว็บ บน iOS ให้ตรวจสอบโครงสร้าง custom URI ทั้งหมด (โดยพึ่งพา Universal Links เมื่อต้องการยืนยันตัวตนโดเมนกับแอป) และปฏิเสธคีย์ query ที่ซ้ำกันบนทั้งสองแพลตฟอร์ม - ใช้ระบบป้องกันหลายชั้นสำหรับป๊อปอัปและสภาวะแข่งขัน (Race Conditions): จำกัดสถานะเซสชันป๊อปอัปของ Android ไว้ที่ UI thread อย่างเคร่งครัด พร้อมทำความเข้าใจขอบเขต callback ข้าม
shouldInterceptRequestและshouldOverrideUrlLoadingและแยกการตรวจสอบนโยบายบริสุทธิ์ออกจากผลกระทบด้านข้างของการส่งต่อภายนอกในWKWebViewของ iOS โดยใช้การลบความซ้ำซ้อนระดับการกระทำและโทเค็นการสร้างการนำทาง
สาเหตุทั่วไปและขั้นตอนการตรวจสอบข้อผิดพลาดในการเปลี่ยนเส้นทาง WebView
การจับคู่ข้อผิดพลาดของไคลเอนต์ที่สังเกตได้กับกลไกความล้มเหลวของคอนเทนเนอร์เบื้องหลัง
ใช้เมทริกการวินิจฉัยด้านล่างเพื่อแมปอาการของ WebView ที่สังเกตได้กับสาเหตุหลักของแพลตฟอร์มทั่วไป, ขั้นตอนการตรวจสอบ และการแก้ไขที่ตรงจุด:
| อาการหรือข้อผิดพลาดที่สังเกตได้ | แพลตฟอร์มเป้าหมาย | สาเหตุหลักทั่วไป | ขั้นตอนการตรวจสอบเพื่อวินิจฉัย | การแก้ไขที่ตรงจุด |
|---|---|---|---|---|
WebView แสดง net::ERR_UNKNOWN_URL_SCHEME |
Android WebView | Custom WebViewClient ส่งค่า false หรือไม่มี allowlist สำหรับ scheme |
ตรวจสอบ request.url ใน shouldOverrideUrlLoading |
ดักจับ URI ที่อยู่ใน allowlist และส่งต่อ Intent.ACTION_VIEW ที่ผูกกับแพ็กเกจแบบ 1 ต่อ 1 |
| ค้างแบบเงียบ ๆ เมื่อแตกลิงก์ custom scheme | iOS WKWebView | WebKit ยกเลิก non-HTTP URI เมื่อ WKNavigationDelegate ส่งค่า .allow |
บันทึก navigationAction.request.url ใน decidePolicyForNavigationAction |
กำหนดเส้นทาง scheme ที่ผ่านการตรวจสอบผ่าน UIApplication.shared.open และส่ง .cancel |
target="_blank" แทนที่หน้าปัจจุบันใน WebView |
Android WebView | setSupportMultipleWindows(false)ปฏิบัติกับหน้าต่างใหม่เสมือนเป็นการโหลดระดับบนสุด (top-level) |
ตรวจสอบ webView.settings.supportMultipleWindows() |
เปิดใช้งาน setSupportMultipleWindows(true) เฉพาะเมื่อต้องการคอนเทนเนอร์ป๊อปอัปแยกต่างหาก |
target="_blank" ไม่ทำงานหรือดรอป OAuth 302 redirects |
Android WebView | ไม่มี onCreateWindow หรือไคลเอนต์ลูกบล็อกฮอป isRedirect ที่ไม่มี hasGesture() |
ตรวจสอบบันทึกของ onCreateWindow, request.isRedirect และ shouldInterceptRequest |
แนบ popup WebView ที่โฮสต์ในวิวกำกับด้วยสถานะเซสชันบน UI thread และฮอป isRedirect ที่มีขอบเขต |
ลิงก์ที่มี target="_blank" หรือ window.open() ไม่ทำงาน |
iOS WKWebView | การนำทางหน้าต่างใหม่ตั้งค่า targetFrame == nil และต้องใช้ WKUIDelegate |
ตรวจสอบ navigationAction.targetFrame == nil |
ตรวจจับ targetFrame == nil ใน decidePolicyForNavigationAction และจัดการผ่าน WKUIDelegate |
| ติดตั้งแอปเป้าหมายแล้ว แต่หน้าเว็บสำรอง (fallback) กลับเปิดขึ้นมาแทน | Android 11+ (targetSdk >= 30) |
การประกาศ <queries> ที่หายไปทำให้ resolveActivity() หรือ queryIntentActivities() ส่งคืนผลลัพธ์ที่ไม่สมบูรณ์สำหรับแพ็กเกจที่มองไม่เห็น |
เพิ่มการบันทึกระดับแอปพลิเคชันรอบ ๆ resolveActivity() และตรวจสอบผลลัพธ์ผ่าน adb logcat |
ประกาศ intent <queries> หากทำการตรวจสอบล่วงหน้า หรือเรียกใช้ startActivity โดยตรงพร้อมกับดักจับ ActivityNotFoundException |
| การเปลี่ยนเส้นทางด้วยตัวจับเวลา JavaScript ไม่สามารถเปิดแอปภายนอกได้ | iOS / Android | การเปลี่ยนเส้นทางด้วยสคริปต์อัตโนมัติขาดสัญญาณการโต้ตอบของผู้ใช้ | ตรวจสอบ request.hasGesture() (Android) หรือ navigationType (iOS) |
ผูกการเปลี่ยนเส้นทางกับการแตะของผู้ใช้โดยตรงและกำหนดนโยบายท่าทางสัมผัสของโฮสต์ที่ชัดเจน |
Universal Link โหลดภายใน WKWebView แทนที่จะเป็นแอปเป้าหมาย |
iOS WKWebView | บริบทการท่องเว็บ ความสัมพันธ์ของโดเมน หรือการนำทางด้วย JS ทำให้การโหลดค้างอยู่ใน WebKit | ตรวจสอบ navigationType และโฮสต์ใน decidePolicyForNavigationAction |
เรียกใช้ UIApplication.shared.open พร้อมกับ .universalLinksOnly: true สำหรับโฮสต์ภายนอกที่อนุญาต |
รายการตรวจสอบการแก้ไขปัญหาด่วนสำหรับการเปลี่ยนเส้นทาง WebView ภายใน 5 นาที
- ขั้นตอนที่ 1: ตรวจสอบ Protocol Scheme ใน DevTools: ตรวจสอบว่าหน้าเว็บส่ง
https://, custom scheme, หรือintent://URI และยืนยันว่าไม่ถูกบล็อกโดย Content Security Policy (CSP) - ขั้นตอนที่ 2: ตรวจสอบลำดับชั้นของเฟรม (Frame Hierarchy): ตรวจสอบว่าตัวทริกเกอร์เริ่มต้นขึ้นภายใน
<iframe>ของบุคคลที่สาม (!isMainFrame) หรือไม่ แอปพลิเคชันโฮสต์อาจบล็อกการเปิดแอปภายนอกที่ริเริ่มจาก iframe ของบุคคลที่สามโดยเจตนา - ขั้นตอนที่ 3: แยกแยะการเปลี่ยนเส้นทาง (Redirects) ออกจากตัวจับเวลา (Timers): ตรวจสอบว่าการนำทางที่ไม่มีท่าทางสัมผัสเป็นการเปลี่ยนเส้นทางเซิร์ฟเวอร์ HTTP 3xx ที่ได้รับอนุญาต (
request.isRedirectบน Android) หรือเป็นตัวจับเวลา JavaScript ที่ไม่มีการกระตุ้น - ขั้นตอนที่ 4: ตรวจสอบตัวทริกเกอร์หน้าต่างใหม่: ยืนยันว่า
target="_blank"หรือwindow.open()สร้างคำขอหน้าต่างใหม่หรือไม่ (targetFrame == nilบน iOS หรือonCreateWindowบน Android) - ขั้นตอนที่ 5: ตรวจสอบการแก้ไขปัญหาแพ็กเกจของ OS: สำหรับแอปที่กำหนดเป้าหมาย API 30+ บน Android 11+ ให้ยืนยันว่าการเรียก
resolveActivity()ล่วงหน้าล้มเหลวเนื่องจากการประกาศ<queries>ที่ขาดหายไปหรือไม่
เวิร์กโฟลว์การวินิจฉัยต่อไปนี้แสดงเส้นทางการแก้ไขปัญหาตามลำดับสำหรับการแยกความล้มเหลวในการเปลี่ยนเส้นทางของคอนเทนเนอร์:
[WebView Navigation Failure]
│
▼
[Inspect URL + Network + Console via Chrome DevTools / Safari Web Inspector]
│
▼
[Identify Navigation Source]
│
├── App loadUrl() or HTTP POST
│ │
│ └── shouldOverrideUrlLoading is NOT invoked; inspect host-side call path
│
├── target="_blank" or window.open()
│ │
│ ├── Android (multiple-windows=false) ──> Replaces current WebView page
│ ├── Android (multiple-windows=true) ──> Inspect onCreateWindow + shouldInterceptRequest
│ └── iOS (targetFrame == nil) ──> Inspect WKNavigationDelegate + WKUIDelegate
│
├── HTTP / HTTPS Navigation
│ │
│ └── Inspect Host + Port Allowlist, 3xx Redirects, Universal Link, or App Link matching
│
└── Custom Scheme or Chrome intent://
│
├── Evaluate User Interaction + Main Frame policy
├── Verify Full URI Structure (Scheme, Host, Port, Path, No Duplicate Query Keys)
├── Sanitize Intent (Reject Explicit Components, Verify 1-to-1 Package, Zero Webpage Flags)
├── Check Target-App Resolution (<queries> / ActivityNotFoundException)
└── Validate Fallback Path + Query Allowlist + Monotonic Chain Guard (elapsedRealtime)
วิธีตรวจสอบอีเวนต์การนำทางของ WebView โดยใช้เครื่องมือดีบักระยะไกล
การเปิดใช้งานการดีบักระยะไกลผ่าน Chrome DevTools และ ADB Logcat บน Android
ก่อนที่จะแก้ไข native delegates ให้ตรวจสอบว่าหน้าเว็บที่โหลดมาปล่อยการเปลี่ยนเส้นทางตามที่คาดไว้หรือไม่ ตาม คู่มือการดีบักระยะไกล WebView ของ Android Chrome DevTools ให้เปิดใช้งานการดีบัก WebView ระยะไกลอย่างชัดเจนในบิวด์สำหรับการพัฒนาโดยการตรวจสอบ ApplicationInfo.FLAG_DEBUGGABLE และเรียกใช้ WebView.setWebContentsDebuggingEnabled(true) ห้ามเผยแพร่บิวด์ที่เปิดใช้งานการดีบักในรุ่นที่ใช้งานจริง (production):
// Android - Enable WebView debugging exclusively in debuggable builds
if (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0) {
WebView.setWebContentsDebuggingEnabled(true)
}
เชื่อมต่ออุปกรณ์ผ่าน USB เปิด chrome://inspect/#devices ในเดสก์ท็อป Chrome และตรวจสอบแท็บ Network โดยทำเครื่องหมายที่ Preserve log ในเวลาเดียวกัน ให้กรองบันทึกรันไทม์เนทีฟผ่าน adb logcat เพื่อจับ ActivityNotFoundException, SecurityException, หรือบันทึก wrapper ที่กำหนดเอง โปรดทราบว่าคำเตือนเรื่องเลิกใช้งาน (deprecation warnings) สำหรับลายเซ็น shouldOverrideUrlLoading(WebView, String) แบบเดิมจะปรากฏขึ้นระหว่างการคอมไพล์ของ Android Studio / Gradle มากกว่าในรันไทม์ adb logcat:
# Terminal - Filter logcat for custom WebView tags and ActivityTaskManager intent resolution
adb logcat -s "WebViewDebug" "ActivityTaskManager" "PackageManager"
การกำหนดค่า isInspectable และการแนบ Safari Web Inspector รวมถึง Xcode Console บน iOS
เริ่มต้นด้วย iOS 16.4 และ macOS 13.3 ทาง Apple กำหนดให้แอปพลิเคชันต้องเลือกเปิดใช้งานผ่าน WKWebView.isInspectable ซึ่งมีค่าเริ่มต้นเป็น false ให้เปิดใช้งาน webView.isInspectable = true ภายในบล็อก #if DEBUG:
// iOS - Enable Safari Web Inspector opt-in on iOS 16.4+ debug builds
#if DEBUG
if #available(iOS 16.4, *) {
webView.isInspectable = true
}
#endif
บนอุปกรณ์ iOS จริง ให้ไปที่ การตั้งค่า > แอป > Safari > ขั้นสูง (ในเวอร์ชัน iOS ที่เก่ากว่าคือ การตั้งค่า > Safari > ขั้นสูง) และเปิดใช้งาน Web Inspector เชื่อมต่อผ่าน USB เปิดเมนู Develop ของเดสก์ท็อป Safari และตรวจสอบ Xcode Console ไปพร้อมกันสำหรับผลลัพธ์การทำงานของ decidePolicyForNavigationAction, createWebViewWith และ UIApplication.shared.open เนทีฟ

การแก้ปัญหาการดรอปหน้าต่างใหม่แบบเงียบๆ และท่าทางสัมผัสของผู้ใช้ที่หายไปใน iOS WKWebView
การแยกการประเมินนโยบายออกจากผลกระทบด้านข้างข้าม WKNavigationDelegate และ WKUIDelegate
เมื่อลิงก์เว็บระบุ target="_blank" หรือ window.open(), WebKit จะสร้างคำขอการนำทางหน้าต่างใหม่โดยที่ navigationAction.targetFrame เป็น nil และเกี่ยวข้องกับทั้ง WKNavigationDelegate และ WKUIDelegate หากแอปโฮสต์ไม่ได้ใช้งาน webView(_:createWebViewWithConfiguration:for:windowFeatures:), WebKit จะไม่สามารถสร้าง WebView สำรองได้ และการนำทางอาจล้มเหลวแบบเงียบ ๆ
เพื่อป้องกันไม่ให้มีการเปิดแอปภายนอกซ้ำหรือโทเค็นการสร้างที่เพิ่มขึ้นสองเท่าเมื่อ delegate ทั้งสองตรวจสอบคำขอ ให้แยก การประเมินนโยบายบริสุทธิ์ (evaluateNavigationPolicy) ออกจาก ผลกระทบด้านข้างของการปฏิบัติงาน (execution side effects) และทำความสะอาดความซ้ำซ้อนด้วยอินสแตนซ์ WKNavigationAction เฉพาะ (ObjectIdentifier(navigationAction)) แทนที่จะพึ่งพาเพียงเกณฑ์เวลาหยาบ ๆ ที่อาจระงับการคลิกซ้ำอย่างรวดเร็วโดยเจตนาของผู้ใช้ ประเมิน navigationAction.targetFrame == nil โดยตรงใน decidePolicyForNavigationAction: หากการประเมินส่งคืนแผนการส่งต่อภายนอก ให้ดำเนินการหนึ่งครั้ง (บันทึกตัวระบุ WKNavigationAction) และส่ง .cancel; หากส่งคืน .allowInWebView สำหรับ URL ป๊อปอัปที่อยู่ใน allowlist ให้ส่ง .allow เพื่อให้ createWebViewWith โหลดป๊อปอัปได้อย่างปลอดภัย ตรวจสอบลำดับการเรียก callback ของ delegate ให้แน่ชัดบนเวอร์ชัน iOS เป้าหมายเสมอ
บริบท Universal Link, ความปลอดภัยจาก Async Race, และเอกลักษณ์ของ Custom Scheme
การส่งต่อ Universal Link ขึ้นอยู่กับบริบทการท่องเว็บของต้นทาง, ความสัมพันธ์ของโดเมน, และการกำหนดค่า Associated Domains (ตรวจสอบผ่านไฟล์ apple-app-site-association ของเซิร์ฟเวอร์เป้าหมาย) บันทึกทางเทคนิค TN3155: Debugging universal links ของ Apple อธิบายว่าการนำทางภายในโดเมนเดียวกันใน Safari เอื้อต่อการอยู่ในเบราว์เซอร์ ในขณะที่ subdomain ที่แตกต่างกันจะเปลี่ยนสิทธิ์ในการเข้าถึง ทดสอบพฤติกรรมของ Associated Domains บนรุ่น iOS เป้าหมายภายใน WKWebView เสมอ
เมื่อเรียกใช้ UIApplication.shared.open(url, options: [.universalLinksOnly: true]) ให้ป้องกันสภาวะแข่งขันแบบอะซิงโครนัส (asynchronous navigation race conditions): หากผู้ใช้เริ่มความพยายามในการนำทางเฟรมหลักใด ๆ ตามหลังในขณะที่ระบบกำลังประมวลผลการส่งต่อ Universal Link, ตัวจัดการ completion handler ที่ไม่มีการป้องกันซึ่งส่งคืนค่า false อาจเขียนทับสถานะการนำทางใหม่ของผู้ใช้ เพิ่มโทเค็น activeNavigationGeneration แบบโมโนโทนิกในการประเมินการนำทางเฟรมหลักใหม่ทุกครั้ง (รวมถึงความพยายามที่ถูกบล็อกหรือเปลี่ยนเส้นทาง) เพื่อให้การสำรองข้อมูลแบบอะซิงโครนัสก่อนหน้าที่รอดำเนินการถูกยกเลิกทันที และตรวจสอบ self.activeNavigationGeneration == requestGeneration ควบคู่ไปกับ self.isViewLoaded && self.view.window != nil ก่อนที่จะโหลด URL สำรองใหม่
สังเกตขอบเขตความปลอดภัยที่เข้มงวดสองประการ:
- การจำแนกประเภท
WKNavigationType: ตามเอกสารประกอบWKNavigationTypeของ Apple,formSubmittedแสดงถึงคำขอส่งฟอร์มแทนที่จะเป็นการแตะลิงก์ และสคริปต์หน้าเว็บสามารถส่งฟอร์มได้โดยโปรแกรม จำกัดการส่งต่อแอปภายนอกให้อยู่ในอีเวนต์.linkActivatedที่จำแนกประเภทโดย WebKit ร่วมกับsourceFrame.isMainFrameและ allowlists ของ URI แบบเต็ม แทนที่จะปฏิบัติต่อ.linkActivatedเป็นโทเค็นท่าทางสัมผัสการเข้ารหัสลับแบบแยกเดี่ยว - ความไม่ซ้ำกันของ Custom Scheme & มลพิษพารามิเตอร์: ตามคู่มือของ Apple เกี่ยวกับ Defining a Custom URL Scheme for Your App แอปหลายตัวสามารถอ้างสิทธิ์ custom scheme เดียวกันได้
isAllowedCustomURL(_:)จะตรวจสอบโครงสร้าง URI (scheme, host, พอร์ตเริ่มต้นnil, รูปแบบพาธ, ไม่มี userinfo/fragment, และปฏิเสธคีย์ query ที่ซ้ำกัน) ไม่ใช่ข้อมูลระบุตัวตน Bundle ID เป้าหมาย ใช้ Universal Links ที่ยืนยันโดเมนแล้วทุกครั้งเมื่อจำเป็นต้องมีการผูกมัดตัวตนของแอป
ข้อจำกัดความรับผิดชอบเกี่ยวกับสถาปัตยกรรมอ้างอิง: การใช้งานต่อไปนี้เป็นสถาปัตยกรรมอ้างอิงแบบป้องกัน ตรวจสอบความพร้อมใช้งานของ API, ลำดับของ delegate และพฤติกรรมวงจรชีวิตเทียบกับเวอร์ชัน AndroidX และ iOS ที่แอปพลิเคชันของคุณใช้จริง
// iOS - WebViewContainerController.swift
// Reference architecture: compile and test against your specific project targets (iOS 15.0–18.0)
import UIKit
import WebKit
final class WebViewContainerController: UIViewController, WKNavigationDelegate, WKUIDelegate {
private enum NavigationPlan: Equatable {
case allowInWebView
case launchCustomScheme(URL)
case attemptUniversalLink(URL)
case block
}
private var webView: WKWebView!
// Explicit allowlist for external custom URL schemes, hosts, and query keys
private let allowedCustomSchemes: Set<String> = ["myapp", "partnerapp"]
private let allowedCustomHosts: Set<String> = ["open", "product", "promo"]
private let allowedCustomQueryKeys: Set<String> = ["id", "ref", "promo"]
// Explicit allowlist for HTTPS hosts permitted inside the primary WebView container
private let allowedWebHosts: Set<String> = [
"example.com",
"m.example.com",
"links.example.com"
]
// Isolated allowlists specifically for child popup windows (target="_blank")
private let allowedPopupHosts: Set<String> = ["example.com", "auth.example.com"]
private let allowedPopupPathPrefixes: [String] = ["/oauth", "/popup", "/window"]
// External Universal Link hosts that attempt native app handoff on link activation
private let externalUniversalLinkHosts: Set<String> = ["links.example.com"]
// Monotonic navigation generation token incremented on every new main-frame navigation attempt
private var activeNavigationGeneration: UInt64 = 0
// Action-level deduplication preventing duplicate dispatches for the same WKNavigationAction
private var dispatchedActionIDs: [ObjectIdentifier] = []
private let maxTrackedActionIDs = 16
// Monotonic-uptime TTL-bounded bypass cache keyed by normalized Universal Link key
private var bypassedUniversalLinkKeys: [String: TimeInterval] = [:]
private let maxBypassedKeys = 10
private let bypassTTLSeconds: TimeInterval = 300
// Adapt significant query keys to match your application's actual routing parameters
private let significantLoopQueryKeys: Set<String> = ["id"]
override func viewDidLoad() {
super.viewDidLoad()
let configuration = WKWebViewConfiguration()
webView = WKWebView(frame: view.bounds, configuration: configuration)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.navigationDelegate = self
webView.uiDelegate = self
#if DEBUG
if #available(iOS 16.4, *) {
webView.isInspectable = true
}
#endif
view.addSubview(webView)
}
// MARK: - WKNavigationDelegate
func webView(
_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
) {
guard let url = navigationAction.request.url else {
decisionHandler(.cancel)
return
}
let isMainFrame = navigationAction.sourceFrame.isMainFrame
let isNewWindow = (navigationAction.targetFrame == nil)
// Increment generation token on every main-frame navigation attempt (including blocked attempts)
// so any pending prior asynchronous Universal Link fallback is invalidated immediately.
if isMainFrame && !isNewWindow {
activeNavigationGeneration &+= 1
}
let requestGeneration = activeNavigationGeneration
let plan = evaluateNavigationPolicy(
url: url,
navigationType: navigationAction.navigationType,
isMainFrame: isMainFrame,
isNewWindow: isNewWindow
)
switch plan {
case .allowInWebView:
decisionHandler(.allow)
case .launchCustomScheme(let targetURL):
if isMainFrame { activeNavigationGeneration &+= 1 }
executeExternalDispatchOnce(
action: navigationAction,
url: targetURL,
isUniversalLink: false,
requestGeneration: activeNavigationGeneration
)
decisionHandler(.cancel)
case .attemptUniversalLink(let targetURL):
if isMainFrame { activeNavigationGeneration &+= 1 }
let currentGen = activeNavigationGeneration
executeExternalDispatchOnce(
action: navigationAction,
url: targetURL,
isUniversalLink: true,
requestGeneration: currentGen
)
decisionHandler(.cancel)
case .block:
decisionHandler(.cancel)
}
}
// MARK: - WKUIDelegate (Handles target="_blank" and window.open)
func webView(
_ webView: WKWebView,
createWebViewWith configuration: WKWebViewConfiguration,
for navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures
) -> WKWebView? {
guard navigationAction.targetFrame == nil,
let url = navigationAction.request.url else {
return nil
}
let isMainFrame = navigationAction.sourceFrame.isMainFrame
if isMainFrame {
activeNavigationGeneration &+= 1
}
let currentGen = activeNavigationGeneration
let plan = evaluateNavigationPolicy(
url: url,
navigationType: navigationAction.navigationType,
isMainFrame: isMainFrame,
isNewWindow: true
)
switch plan {
case .allowInWebView:
webView.load(navigationAction.request)
case .launchCustomScheme(let targetURL):
executeExternalDispatchOnce(
action: navigationAction,
url: targetURL,
isUniversalLink: false,
requestGeneration: currentGen
)
case .attemptUniversalLink(let targetURL):
executeExternalDispatchOnce(
action: navigationAction,
url: targetURL,
isUniversalLink: true,
requestGeneration: currentGen
)
case .block:
break
}
return nil
}
// MARK: - Pure Navigation Policy Evaluation (Zero Side Effects)
private func evaluateNavigationPolicy(
url: URL,
navigationType: WKNavigationType,
isMainFrame: Bool,
isNewWindow: Bool
) -> NavigationPlan {
guard let scheme = url.scheme?.lowercased() else {
return .block
}
let isLinkActivated = (navigationType == .linkActivated)
// 1. Evaluate non-HTTP/HTTPS Custom URL Schemes
// Note: Custom scheme allowlisting validates URI structure; it cannot guarantee target Bundle ID identity.
if scheme != "http" && scheme != "https" {
guard isMainFrame, isLinkActivated, isAllowedCustomURL(url) else {
return .block
}
return .launchCustomScheme(url)
}
// 2. Enforce HTTPS-only, default port (nil or 443), and Host Allowlists
let targetHost = url.host?.lowercased()
if isNewWindow {
guard isMainFrame, isLinkActivated, isAllowedPopupWebURL(url) else {
return .block
}
} else {
guard isAllowedWebURL(url), let host = targetHost, allowedWebHosts.contains(host) else {
return .block
}
}
// 3. Evaluate Universal Link Handoffs for designated external hosts on link activation
if let host = targetHost,
externalUniversalLinkHosts.contains(host),
isMainFrame,
isLinkActivated,
let loopKey = universalLinkLoopKey(for: url),
!isBypassedKeyActive(loopKey) {
return .attemptUniversalLink(url)
}
return .allowInWebView
}
// MARK: - Action-Level Deduplicated External Dispatch Execution
private func executeExternalDispatchOnce(
action: WKNavigationAction,
url: URL,
isUniversalLink: Bool,
requestGeneration: UInt64
) {
let actionID = ObjectIdentifier(action)
if dispatchedActionIDs.contains(actionID) {
return
}
if dispatchedActionIDs.count >= maxTrackedActionIDs {
dispatchedActionIDs.removeFirst()
}
dispatchedActionIDs.append(actionID)
if isUniversalLink {
guard let loopKey = universalLinkLoopKey(for: url) else { return }
UIApplication.shared.open(url, options: [.universalLinksOnly: true]) { [weak self] success in
// Verify view lifecycle AND generation token to prevent stale async fallback overwrites
guard let self = self,
self.isViewLoaded,
self.view.window != nil,
self.activeNavigationGeneration == requestGeneration else {
return
}
if !success {
self.recordBypassedKey(loopKey)
self.webView.load(URLRequest(url: url))
}
}
} else {
UIApplication.shared.open(url, options: [:]) { success in
if !success {
print("[WebViewDebug] Failed to launch custom scheme (app may not be installed)")
}
}
}
}
private func isAllowedWebURL(_ url: URL) -> Bool {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let scheme = components.scheme?.lowercased(),
scheme == "https",
components.user == nil,
components.password == nil,
(components.port == nil || components.port == 443) else {
return false
}
return true
}
private func isAllowedPopupWebURL(_ url: URL) -> Bool {
guard isAllowedWebURL(url),
let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let host = components.host?.lowercased(),
allowedPopupHosts.contains(host),
components.fragment == nil else {
return false
}
let path = components.path
return allowedPopupPathPrefixes.contains { path == $0 || path.hasPrefix("\($0)/") }
}
private func isAllowedCustomURL(_ url: URL) -> Bool {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let scheme = components.scheme?.lowercased(),
let host = components.host?.lowercased(),
allowedCustomSchemes.contains(scheme),
allowedCustomHosts.contains(host),
components.user == nil,
components.password == nil,
components.port == nil, // Reject explicit ports on custom schemes
components.fragment == nil else {
return false
}
let path = components.path
if !path.isEmpty &&
path.range(of: "^/[A-Za-z0-9/_-]{1,64}$", options: .regularExpression) == nil {
return false
}
if let queryItems = components.queryItems {
var seenKeys = Set<String>()
for item in queryItems {
if seenKeys.contains(item.name) {
return false
}
seenKeys.insert(item.name)
guard allowedCustomQueryKeys.contains(item.name),
let value = item.value,
value.count <= 64,
value.range(of: "^[A-Za-z0-9_-]+$", options: .regularExpression) != nil else {
return false
}
}
}
return true
}
private func universalLinkLoopKey(for url: URL) -> String? {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let scheme = components.scheme?.lowercased(),
let host = components.host?.lowercased() else {
return nil
}
let portPart = (components.port != nil && components.port != 443) ? ":\(components.port!)" : ""
let significantParams = (components.queryItems ?? [])
.filter { significantLoopQueryKeys.contains($0.name) }
.sorted { $0.name < $1.name }
.map { "\($0.name)=\($0.value ?? "")" }
.joined(separator: "&")
let querySuffix = significantParams.isEmpty ? "" : "?\(significantParams)"
return "\(scheme)://\(host)\(portPart)\(components.path)\(querySuffix)"
}
private func isBypassedKeyActive(_ key: String) -> Bool {
let now = ProcessInfo.processInfo.systemUptime
bypassedUniversalLinkKeys = bypassedUniversalLinkKeys.filter {
(now - $0.value) < bypassTTLSeconds
}
return bypassedUniversalLinkKeys[key] != nil
}
private func recordBypassedKey(_ key: String) {
let now = ProcessInfo.processInfo.systemUptime
bypassedUniversalLinkKeys = bypassedUniversalLinkKeys.filter {
(now - $0.value) < bypassTTLSeconds
}
if bypassedUniversalLinkKeys.count >= maxBypassedKeys,
let oldestKey = bypassedUniversalLinkKeys.min(by: { $0.value < $1.value })?.key {
bypassedUniversalLinkKeys.removeValue(forKey: oldestKey)
}
bypassedUniversalLinkKeys[key] = now
}
}
การแก้ไข ERR_UNKNOWN_URL_SCHEME และความล้มเหลวในการมองเห็นแพ็กเกจ (Package Visibility) ใน Android WebView
Callback ที่เลิกใช้งานแล้ว, hasGesture() และขอบเขตของ POST
Android ได้เลิกใช้งาน shouldOverrideUrlLoading(WebView, String) ใน API ระดับ 24 และสนับสนุน shouldOverrideUrlLoading(WebView, WebResourceRequest) แทน WebResourceRequest มีคุณสมบัติ isForMainFrame, isRedirect และ hasGesture() โปรดสังเกตข้อจำกัดอย่างเป็นทางการของแพลตฟอร์มสองประการ: shouldOverrideUrlLoading จะไม่ถูกเรียกใช้สำหรับการเรียก webView.loadUrl() ที่ริเริ่มโดยแอป หรือสำหรับการนำทางแบบ HTTP POST และ hasGesture() อาจส่งคืนค่า false สำหรับการเปลี่ยนเส้นทาง JavaScript แบบอะซิงโครนัสที่ถูกต้องหรือฮอปเซิร์ฟเวอร์ 302
การจัดการป๊อปอัปแบบป้องกันหลายชั้นและการแยกเธรดใน WebChromeClient.onCreateWindow
พฤติกรรมป๊อปอัปของ Android ขึ้นอยู่กับ WebSettings.setSupportMultipleWindows หากแอปของคุณไม่ต้องใช้ป๊อปอัปแบบโต้ตอบ การตั้งค่า setSupportMultipleWindows(false) ไว้ (หรือส่งคืน false จาก onCreateWindow) จะช่วยป้องกันไม่ให้ iframe ของบุคคลที่สามเปิดคอนเทนเนอร์สำรอง หรือเปิดปลายทางที่ตรวจสอบแล้วผ่านจุดเข้าใช้งานที่โฮสต์ควบคุมอย่างชัดเจน
เมื่อเปิดใช้งาน setSupportMultipleWindows(true), WebChromeClient.onCreateWindow จะไม่ระบุ URL ปลายทางในลายเซ็น callback และไม่มี callback เดียวที่ครอบคลุมเวกเตอร์การนำทางทั้งหมด การทำความเข้าใจโมเดลเธรดและขอบเขต callback ที่แน่นอนจึงเป็นสิ่งสำคัญสำหรับแนวทางการอ้างอิงแบบป้องกันหลายชั้น:
shouldOverrideUrlLoading(UI Thread — เจ้าของสถานะการนำทางและเซสชัน): ทำงานเฉพาะบน UI thread และเป็นเจ้าของสถานะเซสชันป๊อปอัปที่เปลี่ยนแปลงได้ทั้งหมด (isInitialTransportLoad,isAuthorizedPopupSession,popupRedirectHops, และpopupChainStartMs) เมื่อโหลดเริ่มต้นที่ได้รับการตรวจสอบหรือท่าทางสัมผัสของผู้ใช้โดยตรงตรงกับpolicy.isAllowedPopupUriเท่านั้นshouldOverrideUrlLoadingจึงจะอนุญาตเซสชันสำหรับการเปลี่ยนเส้นทาง HTTP 302 ที่มีขอบเขตในภายหลัง (request.isRedirect) เพื่อให้แน่ใจว่าเชนการเปลี่ยนเส้นทางเชื่อมโยงกลับไปยังเซสชันที่ได้รับอนุญาต แทนที่จะเชื่อถือการเปลี่ยนเส้นทางตามอำเภอใจshouldInterceptRequest(Background WebView IO Thread — ตัวป้องกันแบบอ่านอย่างเดียวไร้สถานะ): ทำงานบนเธรด WebView ที่ไม่ใช่ UI เนื่องจากต้องไม่เปลี่ยนแปลงสถานะเซสชันของ UI thread จึงทำงานอย่างเคร่งครัดในฐานะการตรวจสอบนโยบายแบบอ่านอย่างเดียวและไร้สถานะบนsafeClient.policy(บล็อกคำขอ HTTP/HTTPS ของเฟรมหลักที่ล้มเหลวisAllowedPopupUriและส่งdisposeActivePopup()ไปยัง main thread) โปรดทราบว่าตามเอกสารประกอบของ Android,shouldInterceptRequestจะถูกเรียกใช้เฉพาะสำหรับ URL ของทรัพยากรเริ่มต้นเท่านั้น ไม่ใช่ สำหรับ URL เปลี่ยนเส้นทาง HTTP 302 ในภายหลัง URL เปลี่ยนเส้นทางในภายหลังจะต้องประเมินโดยshouldOverrideUrlLoadingonPageStarted(UI Thread — การตรวจสอบการสำรองข้อมูลเมื่อเริ่มต้นการนำทาง): ดำเนินการเมื่อการโหลดเฟรมหลักเริ่มต้นขึ้น (ไม่ใช่ในฐานะตัวกรองก่อนการนำทาง) โดยจะอัปเดตแบนเนอร์ต้นทางที่มองเห็นได้เพื่อความโปร่งใสของผู้ใช้ และให้การตรวจสอบสำรองเมื่อเริ่มต้นการนำทางโดยเรียกstopLoading()และdisposeActivePopup()หากปลายทางที่ไม่ได้รับอนุมัติเริ่มโหลด
ทดสอบ URL เริ่มต้นที่เป็นอันตราย, เชน HTTP 302 ข้ามโดเมน, การเปลี่ยนเส้นทาง 302 ต่อเนื่อง, target="_blank", window.open(), และตัวทริกเกอร์ iframe ของบุคคลที่สามบนบิวด์ WebView ทางกายภาพเป้าหมายเสมือนจริงเสมอ
การมองเห็นแพ็กเกจบน Android 11+ และคำแนะนำเกี่ยวกับ canOpenURL ที่เลิกใช้งานแล้ว
ภายใต้ กฎการมองเห็นแพ็กเกจ ของ Android, แอปพลิเคชันที่ทำงานบน Android 11 (API ระดับ 30) ขึ้นไป และกำหนดเป้าหมาย API ระดับ 30 ขึ้นไป (targetSdk >= 30) จะได้รับผลลัพธ์เป็น null หรือว่างเปล่าจาก intent.resolveActivity() หรือ queryIntentActivities() เว้นแต่จะประกาศแอปเป้าหมายภายใต้ <queries> ใน AndroidManifest.xml ทาง Android แนะนำให้เรียกใช้ startActivity(intent) โดยตรงภายในบล็อก try/catch สำหรับ ActivityNotFoundException และ SecurityException แทนที่จะขยาย <queries>
บน iOS ทาง Apple ได้เลิกใช้งาน UIApplication.canOpenURL(_:) แล้ว และแนะนำให้ลองเรียกใช้ UIApplication.shared.open(_:options:completionHandler:) โดยตรงพร้อมกับจัดการข้อผิดพลาดใด ๆ ใน completion handler (หรือย้ายไปใช้ Universal Links เพื่อลบการตรวจสอบล่วงหน้าของ scheme) LSApplicationQueriesSchemes ใน Info.plist จะจำเป็นก็ต่อเมื่อโค้ดเดิมยังคงเรียกใช้ canOpenURL(_:) ในขณะที่ open(_:options:completionHandler:) ไม่จำเป็นต้องประกาศ scheme ใน Info.plist ทั้ง <queries> และ LSApplicationQueriesSchemes ควบคุมการมองเห็นคิวรี แต่ไม่ใช่ allowlists ความปลอดภัยสำหรับตรวจสอบความถูกต้องของ URI เว็บที่ไม่น่าเชื่อถือ
<!-- Manifest Fragment: Merge <queries> into your existing AndroidManifest.xml -->
<!-- Required for targetSdk >= 30 on Android 11+ ONLY if calling resolveActivity or queryIntentActivities -->
<queries>
<intent>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" />
</intent>
<intent>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="partnerapp" />
</intent>
</queries>
<!-- Info.plist Fragment: Insert under the root <dict> in Info.plist -->
<!-- Legacy: Required on iOS ONLY if calling deprecated UIApplication.shared.canOpenURL; open(_:options:completionHandler:) does not require this key -->
<key>LSApplicationQueriesSchemes</key>
<array>
<string>myapp</string>
<string>partnerapp</string>
</array>
วิธีแยกวิเคราะห์ Chrome Intent URI อย่างปลอดภัยและป้องกันวงวนการเปลี่ยนเส้นทาง
การรักษาความปลอดภัย Intent.parseUri จากการโจมตีการเปลี่ยนเส้นทาง Intent
URI แบบ intent:// ของ Android จะเข้ารหัส scheme เป้าหมาย, แพ็กเกจ และ URL สำรอง (S.browser_fallback_url) การแยกวิเคราะห์ URI เว็บที่ไม่น่าเชื่อถือผ่าน Intent.parseUri(rawUri, Intent.URI_INTENT_SCHEME) จะนำไปสู่ความเสี่ยงด้าน การเปลี่ยนเส้นทาง Intent (Intent Redirection) ซึ่งมีรายละเอียดอยู่ใน คู่มือความปลอดภัยการเปลี่ยนเส้นทาง Intent ของ Android และ คู่มือการทดสอบความปลอดภัยแอปพลิเคชันมือถือของ OWASP (OWASP MASTG) แม้ว่า Android 16 (API 36) จะเพิ่มการป้องกันค่าเริ่มต้นระดับแพลตฟอร์ม แต่แอปพลิเคชันก็ยังต้องบังคับใช้การตรวจสอบที่เข้มงวดก่อนที่จะส่ง Intent ออกไป

ในการใช้งานการตรวจสอบแบบ fail-closed โดยใช้ AndroidX IntentSanitizer (androidx.core:core:1.9.0+ หรือ androidx.core:core-ktx:1.9.0+ ซึ่งรวม androidx.core:core ไว้ด้วย) โดยไม่ให้เกิดข้อขัดแย้งเรื่องการผูกขาดร่วมกัน (mutual-exclusion conflicts) ของตัวสร้าง (builder) ระหว่าง allowAnyComponent() และเมธอด allowlist ของแพ็กเกจ/คอมโพเนนต์:
- การตรวจสอบก่อนการทำความสะอาด (Pre-Sanitization Checks): ปฏิเสธ intent ที่มีฟิลด์
componentหรือselectorที่ไม่ใช่ค่าว่างทันที (parsedIntent.component != null || parsedIntent.selector != null) แยกและลบbrowser_fallback_urlออกก่อนทำการ sanitize และตรวจสอบในระดับเนทีฟว่าparsedIntent.data?.schemeแมปแบบ 1 ต่อ 1 กับparsedIntent.packageผ่านcustomSchemeTargetPackages(เพื่อให้แน่ใจว่าmyapp://แปลงเป็นcom.example.targetเท่านั้นและไม่ใช่แพ็กเกจของพาร์ทเนอร์รายอื่น) - การทำงานของตัวล้างข้อมูล (Sanitizer Execution): ล้างค่า
parsedIntent.package = nullบนสำเนาที่ไม่น่าเชื่อถือชั่วคราว ดำเนินการIntentSanitizer.Builder().allowAnyComponent().allowAction(Intent.ACTION_VIEW).allowCategory(Intent.CATEGORY_BROWSABLE).allowData { ... }.build().sanitizeByThrowing(parsedIntent)(โดยไม่มีแฟล็กงานที่จัดเตรียมโดยหน้าเว็บ) และกำหนดค่าexpectedPackageและCATEGORY_BROWSABLEที่ผ่านการตรวจสอบแล้วกลับเข้าไปใหม่บน Intent ที่โฮสต์เป็นเจ้าของซึ่งผ่านการ sanitize แล้ว ก่อนการยืนยันหลังการทำความสะอาด - แฟล็กการเปิดใช้งานที่ตระหนักถึงบริบท (Context-Aware Launch Flags): แทรก
Intent.FLAG_ACTIVITY_NEW_TASKภายใน native dispatcher (launchWithContextSafety) เฉพาะเมื่อview.context !is Activityสำหรับการตรวจสอบความสัมพันธ์ระหว่างโดเมนกับแอป ให้เลือกใช้ Android App Links แบบ HTTPS ที่ได้รับการตรวจสอบแล้ว (assetlinks.json)
การป้องกันวงวนสำรองที่ไม่มีที่สิ้นสุดด้วยสถานะเชนแบบโมโนโทนิก
เมื่อ startActivityโยน ActivityNotFoundException ให้ตรวจสอบ browser_fallback_url ด้วยการตรวจสอบ isAllowedFallbackUri(uri) เฉพาะ (เป็น HTTPS อย่างเคร่งครัด, พอร์ตเริ่มต้น, โฮสต์ที่ตรวจสอบแล้ว, คำนำหน้าพาธสำรองที่ชัดเจน, ไม่มีคีย์ query ซ้ำ และไม่มี fragment) ปฏิเสธการแสดงพอร์ตที่ชัดเจนบน custom schemes โดยการตรวจสอบทั้ง uri.port == -1 และ !uri.encodedAuthority.orEmpty().contains(":")
ติดตามเชนสำรองโดยใช้ SystemClock.elapsedRealtime() (หลีกเลี่ยงการกระโดดของ wall-clock System.currentTimeMillis()), แยกเชนผ่าน fallbackLoopKey() (ไม่ใช่การทำ canonicalization แบบเต็มตาม IETF RFC 3986), รีเซ็ตสถานะผ่าน host wrapper loadNewNavigation(webView, url) ที่ชัดเจน และส่งเส้นทางป๊อปอัปสำรองไปยังคอนเทนเนอร์หลักผ่าน onPopupFallbackHandoff เพื่อไม่ให้โดเมนที่ไม่ได้รับอนุญาตโหลดภายในกล่องโต้ตอบป๊อปอัป
ข้อจำกัดความรับผิดชอบเกี่ยวกับสถาปัตยกรรมอ้างอิง: การใช้งานต่อไปนี้เป็นสถาปัตยกรรมอ้างอิงแบบป้องกัน ตรวจสอบความพร้อมใช้งานของ API, ลำดับของ delegate และพฤติกรรมวงจรชีวิตเทียบกับเวอร์ชัน AndroidX และ iOS ที่แอปพลิเคชันของคุณใช้จริง
// Android - SafeWebViewModules.kt
// Reference architecture: compile and test against your specific project targets
// Requires androidx.core:core:1.9.0+ (or androidx.core:core-ktx:1.9.0+) for IntentSanitizer; targets minSdk >= 24.
package com.example.hostapp.webview
import android.app.Activity
import android.app.Dialog
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.net.Uri
import android.os.Bundle
import android.os.Message
import android.os.SystemClock
import android.util.Log
import android.view.ViewGroup
import android.widget.TextView
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.IntentSanitizer
import java.io.ByteArrayInputStream
import java.net.URISyntaxException
// 1. Policy Module (Immutable / Thread-Safe for read-only access from IO & UI threads)
class CustomUriPolicy(
val customSchemeTargetPackages: Map<String, String> = mapOf(
"myapp" to "com.example.target",
"partnerapp" to "com.partner.app"
),
val allowedCustomHosts: Set<String> = setOf("open", "product", "promo"),
val allowedCustomQueryKeys: Set<String> = setOf("id", "ref", "promo"),
val allowedWebHosts: Set<String> = setOf("example.com", "downloads.example.com"),
val allowedFallbackHosts: Set<String> = setOf("downloads.example.com", "example.com"),
val allowedFallbackPathPrefixes: List<String> = listOf("/download", "/app", "/landing"),
val allowedFallbackQueryKeys: Set<String> = setOf("id", "ref", "promo", "utm_source"),
// Isolated allowlists explicitly for popup windows; distinct from general web hosts
val allowedPopupHosts: Set<String> = setOf("example.com", "auth.example.com"),
val allowedPopupPathPrefixes: List<String> = listOf("/oauth", "/popup", "/window")
) {
val allowedCustomSchemes: Set<String> get() = customSchemeTargetPackages.keys
val allowedTargetPackages: Set<String> get() = customSchemeTargetPackages.values.toSet()
private val pathPattern = Regex("^/[A-Za-z0-9/_-]{1,64}$")
private val queryValuePattern = Regex("^[A-Za-z0-9_-]{1,64}$")
fun isAllowedWebUri(uri: Uri): Boolean {
val scheme = uri.scheme?.lowercase() ?: return false
val host = uri.host?.lowercase() ?: return false
return scheme == "https" &&
host in allowedWebHosts &&
(uri.port == -1 || uri.port == 443) &&
uri.userInfo == null
}
fun isAllowedPopupUri(uri: Uri): Boolean {
val scheme = uri.scheme?.lowercase() ?: return false
val host = uri.host?.lowercase() ?: return false
if (scheme != "https" || host !in allowedPopupHosts) return false
if ((uri.port != -1 && uri.port != 443) || uri.userInfo != null || uri.fragment != null) return false
val path = uri.path.orEmpty()
return allowedPopupPathPrefixes.any { path == it || path.startsWith("$it/") } && pathPattern.matches(path)
}
fun isAllowedFallbackUri(uri: Uri): Boolean {
val scheme = uri.scheme?.lowercase() ?: return false
val host = uri.host?.lowercase() ?: return false
if (scheme != "https" || host !in allowedFallbackHosts) return false
if ((uri.port != -1 && uri.port != 443) || uri.userInfo != null || uri.fragment != null) {
return false
}
val path = uri.path.orEmpty()
if (allowedFallbackPathPrefixes.none { path == it || path.startsWith("$it/") } ||
!pathPattern.matches(path)
) {
return false
}
// Validate query keys, enforce value syntax, and reject duplicate keys
val queryNames = uri.queryParameterNames
for (paramName in queryNames) {
if (paramName !in allowedFallbackQueryKeys) return false
val values = uri.getQueryParameters(paramName)
if (values.size != 1 || !queryValuePattern.matches(values[0])) return false
}
return true
}
fun isAllowedCustomUri(uri: Uri): Boolean {
val scheme = uri.scheme?.lowercase() ?: return false
val host = uri.host?.lowercase() ?: return false
if (scheme !in allowedCustomSchemes || host !in allowedCustomHosts) return false
// Reject network ports strictly by checking both uri.port == -1 and raw authority colon absence
val rawAuthority = uri.encodedAuthority.orEmpty()
if (uri.userInfo != null || uri.port != -1 || rawAuthority.contains(":") || uri.fragment != null) {
return false
}
val path = uri.path.orEmpty()
if (path.isNotEmpty() && !pathPattern.matches(path)) return false
// Validate query keys, enforce value syntax, and reject duplicate keys
val queryNames = uri.queryParameterNames
for (paramName in queryNames) {
if (paramName !in allowedCustomQueryKeys) return false
val values = uri.getQueryParameters(paramName)
if (values.size != 1 || !queryValuePattern.matches(values[0])) return false
}
return true
}
}
// 2. Fallback Manager: Monotonic Elapsed-Time Chain State (Isolates active chain from repeat sessions)
class FallbackLoopGuard(
private val maxHopsPerChain: Int = 3,
private val chainTtlMs: Long = 30_000L,
private val significantQueryKeys: Set<String> = setOf("id")
) {
private var chainStartElapsedMs: Long = 0L
private var fallbackHopCount: Int = 0
private val visitedInCurrentChain = mutableSetOf<String>()
fun resetChain() {
chainStartElapsedMs = 0L
fallbackHopCount = 0
visitedInCurrentChain.clear()
}
fun canLoadFallback(uri: Uri, currentWebViewUrl: String?): Boolean {
val now = SystemClock.elapsedRealtime()
if (chainStartElapsedMs == 0L || (now - chainStartElapsedMs) > chainTtlMs) {
chainStartElapsedMs = now
fallbackHopCount = 0
visitedInCurrentChain.clear()
}
val loopKey = fallbackLoopKey(uri)
val currentKey = currentWebViewUrl?.let { fallbackLoopKey(Uri.parse(it)) }
if (fallbackHopCount >= maxHopsPerChain ||
loopKey == currentKey ||
loopKey in visitedInCurrentChain
) {
return false
}
visitedInCurrentChain.add(loopKey)
fallbackHopCount++
return true
}
// Application-level loop key normalizing default HTTPS port and preserving significant query keys
private fun fallbackLoopKey(uri: Uri): String {
val scheme = uri.scheme?.lowercase().orEmpty()
val host = uri.host?.lowercase().orEmpty()
val portSuffix = if (uri.port != -1 && uri.port != 443) ":${uri.port}" else ""
val path = uri.path.orEmpty()
val sigParams = uri.queryParameterNames
.filter { it in significantQueryKeys }
.sorted()
.joinToString("&") { key -> "$key=${uri.getQueryParameter(key).orEmpty()}" }
val querySuffix = if (sigParams.isEmpty()) "" else "?$sigParams"
return "$scheme://$host$portSuffix$path$querySuffix"
}
}
// 3. Router & Fail-Closed IntentSanitizer WebViewClient (UI Thread Only)
class SafeRedirectWebViewClient(
val policy: CustomUriPolicy = CustomUriPolicy(),
val loopGuard: FallbackLoopGuard = FallbackLoopGuard(),
private val onPopupFallbackHandoff: ((fallbackUri: Uri) -> Unit)? = null
) : WebViewClient() {
// Explicit host-initiated navigation API that resets fallback chain state prior to loadUrl()
fun loadNewNavigation(webView: WebView, url: String) {
val targetUri = Uri.parse(url)
if (!policy.isAllowedWebUri(targetUri)) {
Log.w("WebViewDebug", "Blocked host-initiated navigation to untrusted URL")
return
}
loopGuard.resetChain()
webView.loadUrl(url)
}
// Dedicated fallback loader with internal validation preserving active chain state
fun loadFallbackNavigation(webView: WebView, fallbackUri: Uri) {
if (!policy.isAllowedFallbackUri(fallbackUri)) {
Log.w("WebViewDebug", "Blocked untrusted fallback navigation attempt")
return
}
webView.loadUrl(fallbackUri.toString())
}
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
return handleNavigation(
view = view,
uri = request.url,
isForMainFrame = request.isForMainFrame,
hasUserGesture = request.hasGesture(),
isPopupContext = false
)
}
fun handleNavigation(
view: WebView,
uri: Uri?,
isForMainFrame: Boolean,
hasUserGesture: Boolean,
isPopupContext: Boolean
): Boolean {
val targetUri = uri ?: return true
val scheme = targetUri.scheme?.lowercase() ?: return true
// 1. Enforce HTTPS-only & Web Host Allowlist on all HTTP/HTTPS navigations
if (scheme == "http" || scheme == "https") {
if (!policy.isAllowedWebUri(targetUri)) {
Log.w("WebViewDebug", "Blocked non-HTTPS, custom-port, or untrusted web host")
return true
}
if (hasUserGesture && isForMainFrame) {
loopGuard.resetChain()
}
return false
}
// 2. Enforce main-frame and user-gesture constraints on external app launches
if (!isForMainFrame || !hasUserGesture) {
Log.w("WebViewDebug", "Blocked non-main-frame or non-gesture scheme: $scheme")
return true
}
// 3. Parse and fail-closed sanitize Chrome intent:// URIs
if (scheme == "intent") {
return handleIntentUri(view, targetUri.toString(), isPopupContext)
}
// 4. Validate and explicitly bind allowlisted custom URL schemes to 1-to-1 verified target packages
if (policy.isAllowedCustomUri(targetUri)) {
val expectedPackage = policy.customSchemeTargetPackages[scheme] ?: return true
val viewIntent = Intent(Intent.ACTION_VIEW, targetUri).apply {
addCategory(Intent.CATEGORY_BROWSABLE)
`package` = expectedPackage
}
launchIntentSafely(view, viewIntent)
return true
}
// 5. Block all unrecognized schemes
Log.w("WebViewDebug", "Blocked unrecognized URL scheme: $scheme")
return true
}
// UI-Thread Navigation Evaluator for child popup WebViews tying 302 redirects to authorized sessions
fun handlePopupNavigation(
view: WebView,
uri: Uri?,
isForMainFrame: Boolean,
hasUserGesture: Boolean,
isRedirect: Boolean,
isInitialTransportLoad: Boolean,
isAuthorizedPopupSession: Boolean,
onAuthorizedInitialSession: () -> Unit,
canProceedPopupRedirect: () -> Boolean
): Boolean {
val targetUri = uri ?: return true
val scheme = targetUri.scheme?.lowercase() ?: return true
if (scheme == "http" || scheme == "https") {
if (!isForMainFrame) {
Log.w("WebViewDebug", "Blocked subframe HTTPS navigation inside popup")
return true
}
if (!policy.isAllowedPopupUri(targetUri)) {
Log.w("WebViewDebug", "Blocked untrusted popup HTTPS host or path navigation")
return true
}
// Authorize session only on UI thread when initial load or user tap matches allowlist
if (isInitialTransportLoad || hasUserGesture) {
onAuthorizedInitialSession()
return false
}
// Permit bounded server-side 302 redirects ONLY for previously authorized popup sessions
if (isRedirect && isAuthorizedPopupSession && canProceedPopupRedirect()) {
return false
}
Log.w("WebViewDebug", "Blocked unauthorized redirect or non-gesture popup navigation")
return true
}
return handleNavigation(view, targetUri, isForMainFrame, hasUserGesture, isPopupContext = true)
}
private fun handleIntentUri(view: WebView, rawUri: String, isPopupContext: Boolean): Boolean {
val parsedIntent = try {
Intent.parseUri(rawUri, Intent.URI_INTENT_SCHEME)
} catch (e: URISyntaxException) {
Log.w("WebViewDebug", "Malformed intent URI syntax")
return true
}
val fallbackUrl = parsedIntent.getStringExtra("browser_fallback_url")
parsedIntent.removeExtra("browser_fallback_url")
// 1-to-1 Binding: Extract target scheme and validate natively against expected target package
val dataUri = parsedIntent.data ?: return true
val targetScheme = dataUri.scheme?.lowercase() ?: return true
val expectedPackage = policy.customSchemeTargetPackages[targetScheme] ?: run {
Log.w("WebViewDebug", "Blocked intent with unmapped custom scheme: $targetScheme")
return true
}
val rawPackage = parsedIntent.`package`
if (rawPackage != expectedPackage) {
Log.w("WebViewDebug", "Blocked intent package mismatch: expected $expectedPackage")
return true
}
// Reject webpage-specified explicit components and selectors immediately
if (parsedIntent.component != null || parsedIntent.selector != null) {
Log.w("WebViewDebug", "Blocked intent with explicit component or selector")
return true
}
// Clear verified package temporarily before invoking IntentSanitizer with allowAnyComponent()
// to avoid Builder mutual-exclusion constraints while strictly rejecting untrusted flags/extras.
parsedIntent.`package` = null
val sanitizedIntent = try {
IntentSanitizer.Builder()
.allowAnyComponent()
.allowAction(Intent.ACTION_VIEW)
.allowCategory(Intent.CATEGORY_BROWSABLE)
.allowData { uri -> policy.isAllowedCustomUri(uri) }
.build()
.sanitizeByThrowing(parsedIntent)
} catch (e: SecurityException) {
Log.w("WebViewDebug", "IntentSanitizer threw SecurityException for disallowed fields or flags")
return true
} catch (e: IllegalArgumentException) {
Log.w("WebViewDebug", "IntentSanitizer rejected invalid intent arguments")
return true
}
// Re-bind verified target package + host-enforced category + post-sanitization assertions
sanitizedIntent.`package` = expectedPackage
sanitizedIntent.addCategory(Intent.CATEGORY_BROWSABLE)
val sanitizedData = sanitizedIntent.data
if (sanitizedIntent.component != null ||
sanitizedIntent.action != Intent.ACTION_VIEW ||
sanitizedIntent.`package` != expectedPackage ||
sanitizedData == null ||
!policy.isAllowedCustomUri(sanitizedData)
) {
Log.w("WebViewDebug", "Post-sanitization intent assertions failed")
return true
}
try {
launchWithContextSafety(view, sanitizedIntent)
loopGuard.resetChain()
} catch (e: ActivityNotFoundException) {
if (!fallbackUrl.isNullOrBlank()) {
val fallbackUri = Uri.parse(fallbackUrl)
if (policy.isAllowedFallbackUri(fallbackUri) &&
loopGuard.canLoadFallback(fallbackUri, view.url)
) {
if (isPopupContext) {
onPopupFallbackHandoff?.invoke(fallbackUri)
} else {
loadFallbackNavigation(view, fallbackUri)
}
} else {
Log.w("WebViewDebug", "Blocked untrusted or looping fallback URL")
}
}
} catch (e: SecurityException) {
Log.w("WebViewDebug", "SecurityException blocked intent launch")
}
return true
}
private fun launchIntentSafely(view: WebView, intent: Intent) {
try {
launchWithContextSafety(view, intent)
} catch (e: ActivityNotFoundException) {
Log.i("WebViewDebug", "No installed application handles target package/scheme")
} catch (e: SecurityException) {
Log.w("WebViewDebug", "SecurityException blocked custom scheme launch")
}
}
private fun launchWithContextSafety(view: WebView, intent: Intent) {
val safeIntent = Intent(intent)
if (view.context !is Activity) {
safeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
view.context.startActivity(safeIntent)
}
}
// 4. Lifecycle-Managed Popup WebChromeClient (Strict UI-Thread Session State & Stateless Background Guard)
class SafePopupWebChromeClient(
private val safeClient: SafeRedirectWebViewClient
) : WebChromeClient() {
private var activeDialog: Dialog? = null
private var activeChildWebView: WebView? = null
private var isDisposed: Boolean = false
private fun disposeActivePopup() {
if (isDisposed) return
isDisposed = true
val dialog = activeDialog
val child = activeChildWebView
activeDialog = null
activeChildWebView = null
dialog?.setOnDismissListener(null)
dialog?.dismiss()
child?.let {
(it.parent as? ViewGroup)?.removeView(it)
it.stopLoading()
it.webViewClient = WebViewClient()
it.webChromeClient = null
it.destroy()
}
}
override fun onCreateWindow(
view: WebView,
isDialog: Boolean,
isUserGesture: Boolean,
resultMsg: Message?
): Boolean {
if (!isUserGesture) return false
val activity = view.context as? Activity
if (activity == null || activity.isFinishing || activity.isDestroyed) {
return false
}
val transport = resultMsg?.obj as? WebView.WebViewTransport ?: return false
disposeActivePopup()
isDisposed = false
val popupDialog = Dialog(activity)
val popupRoot = android.widget.LinearLayout(activity).apply {
orientation = android.widget.LinearLayout.VERTICAL
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
val originBanner = TextView(activity).apply {
setPadding(24, 16, 24, 16)
setBackgroundColor(android.graphics.Color.DKGRAY)
setTextColor(android.graphics.Color.WHITE)
textSize = 12f
text = "Loading destination..."
}
popupRoot.addView(originBanner)
// All popup session state variables below are read and mutated strictly on the UI thread
var isInitialTransportLoad = true
var isAuthorizedPopupSession = false
var popupRedirectHops = 0
var popupChainStartMs = SystemClock.elapsedRealtime()
val maxPopupRedirects = 5
val maxPopupRedirectWindowMs = 30_000L
val childWebView = WebView(activity).apply {
layoutParams = android.widget.LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
settings.apply {
javaScriptEnabled = true
allowFileAccess = false
allowContentAccess = false
setSupportMultipleWindows(false)
}
webViewClient = object : WebViewClient() {
// UI Thread: Owns navigation, redirect, and session authorization state
override fun shouldOverrideUrlLoading(
childView: WebView,
request: WebResourceRequest
): Boolean {
val hasGesture = request.hasGesture()
if (hasGesture) {
popupRedirectHops = 0
popupChainStartMs = SystemClock.elapsedRealtime()
}
val result = safeClient.handlePopupNavigation(
view = childView,
uri = request.url,
isForMainFrame = request.isForMainFrame,
hasUserGesture = hasGesture,
isRedirect = request.isRedirect,
isInitialTransportLoad = isInitialTransportLoad,
isAuthorizedPopupSession = isAuthorizedPopupSession,
onAuthorizedInitialSession = {
isAuthorizedPopupSession = true
},
canProceedPopupRedirect = {
val withinWindow = (SystemClock.elapsedRealtime() - popupChainStartMs) <= maxPopupRedirectWindowMs
if (withinWindow && popupRedirectHops < maxPopupRedirects) {
popupRedirectHops++
true
} else {
false
}
}
)
isInitialTransportLoad = false
return result
}
// Background WebView IO Thread: Strictly stateless, read-only policy check.
// Never mutates UI-thread session state; covers initial resource URL only (not subsequent 302 hops).
override fun shouldInterceptRequest(
childView: WebView,
request: WebResourceRequest
): WebResourceResponse? {
if (request.isForMainFrame) {
val targetUri = request.url
val scheme = targetUri?.scheme?.lowercase()
if ((scheme == "http" || scheme == "https") && !safeClient.policy.isAllowedPopupUri(targetUri)) {
Log.w("WebViewDebug", "Blocked unapproved popup main-frame request in shouldInterceptRequest")
childView.post { disposeActivePopup() }
return WebResourceResponse("text/plain", "utf-8", ByteArrayInputStream(ByteArray(0)))
}
}
return super.shouldInterceptRequest(childView, request)
}
// UI Thread: Navigation-start fallback check & origin display (not a pre-navigation filter)
override fun onPageStarted(childView: WebView, url: String?, favicon: android.graphics.Bitmap?) {
super.onPageStarted(childView, url, favicon)
isInitialTransportLoad = false
val uri = url?.let { Uri.parse(it) }
if (uri == null || !safeClient.policy.isAllowedPopupUri(uri)) {
Log.w("WebViewDebug", "Navigation-start fallback check terminated unapproved popup URL")
childView.stopLoading()
disposeActivePopup()
return
}
isAuthorizedPopupSession = true
val scheme = uri.scheme?.lowercase() ?: "https"
val host = uri.host?.lowercase() ?: "Unknown"
originBanner.text = "Origin: $scheme://$host"
}
}
webChromeClient = object : WebChromeClient() {
override fun onCloseWindow(window: WebView?) {
disposeActivePopup()
}
}
}
popupRoot.addView(childWebView)
popupDialog.setContentView(popupRoot)
popupDialog.setOnDismissListener {
disposeActivePopup()
}
activeDialog = popupDialog
activeChildWebView = childWebView
popupDialog.show()
transport.webView = childWebView
resultMsg.sendToTarget()
return true
}
fun destroyPopups() {
disposeActivePopup()
}
}
// 5. Complete Host Activity Registration & Lifecycle Cleanup Example (JavaScript Enabled on Main WebView)
class SafeWebViewActivity : AppCompatActivity() {
private lateinit var webView: WebView
private lateinit var safeClient: SafeRedirectWebViewClient
private lateinit var popupChromeClient: SafePopupWebChromeClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0) {
WebView.setWebContentsDebuggingEnabled(true)
}
val policy = CustomUriPolicy()
val loopGuard = FallbackLoopGuard()
safeClient = SafeRedirectWebViewClient(
policy = policy,
loopGuard = loopGuard,
onPopupFallbackHandoff = { fallbackUri ->
popupChromeClient.destroyPopups()
safeClient.loadFallbackNavigation(webView, fallbackUri)
}
)
popupChromeClient = SafePopupWebChromeClient(safeClient)
webView = WebView(this).apply {
settings.apply {
// Enable JavaScript explicitly for trusted landing pages requiring JS redirects or window.open()
javaScriptEnabled = true
allowFileAccess = false
allowContentAccess = false
// Enable multiple windows only if hosting interactive popup containers
setSupportMultipleWindows(true)
}
webViewClient = safeClient
webChromeClient = popupChromeClient
}
setContentView(webView)
// Use explicit host wrapper rather than bare webView.loadUrl()
safeClient.loadNewNavigation(webView, "https://example.com/landing")
}
override fun onDestroy() {
popupChromeClient.destroyPopups()
(webView.parent as? ViewGroup)?.removeView(webView)
webView.destroy()
super.onDestroy()
}
}
คำถามที่พบบ่อย (FAQ)
เหตุใด Android WebView จึงแสดง net::ERR_UNKNOWN_URL_SCHEME แม้ว่าจะติดตั้งแอปเป้าหมายแล้วก็ตาม
เหตุใด shouldOverrideUrlLoading จึงไม่ทำงานเมื่อแอปของฉันเรียกใช้ WebView loadUrl โดยตรง
เหตุใดลิงก์ target blank ที่มี custom schemes จึงล้มเหลวแบบเงียบ ๆ ภายใน WKWebView
สรุปและกรอบการตัดสินใจ
การแก้ไขความล้มเหลวในการเปลี่ยนเส้นทาง deep-linking ของ WebView จำเป็นต้องแยกพฤติกรรมของเอนจิ้น WebView ออกจากนโยบายการนำทางของแอปพลิเคชันโฮสต์ ด้วยการจำลองอีเวนต์การนำทางใน Chrome DevTools หรือ Safari Web Inspector, การจำกัดสถานะเซสชันป๊อปอัปของ Android ไว้ที่ UI thread อย่างเคร่งครัด พร้อมกับการจับคู่การคัดกรองคำขอเริ่มต้นแบบไร้สถานะกับการตรวจสอบการเปลี่ยนเส้นทาง 302 ที่ได้รับอนุญาตจากเซสชัน, การบังคับใช้ allowlists ของ IntentSanitizer แบบ fail-closed, และการปกป้องการสำรองข้อมูล Universal Link ของ iOS จากการเขียนทับแบบอะซิงโครนัสที่ล้าสมัยและการเรียกใช้ delegate ซ้ำ ทีมวิศวกรสามารถลดเส้นทางของผู้ใช้ที่เสียหายและช่วยป้องกันช่องโหว่การเปลี่ยนเส้นทางฝั่งไคลเอนต์ได้
หลังจากที่ตรวจสอบ native delegates ระดับคอนเทนเนอร์และเส้นทางสำรองแล้ว ทีมวิศวกรควรตรวจสอบหน้า landing page การระบุแหล่งที่มาแบบ end-to-end และเชนการกำหนดเส้นทาง One-Click Launch โดยใช้แพลตฟอร์มเช่น OpoInstall เพื่อยืนยันการคงอยู่ของพารามิเตอร์ข้ามการเปลี่ยนผ่านจากเบราว์เซอร์ไปยังแอป
อภิธานศัพท์เอนทิตี
| คำศัพท์ | คำจำกัดความ | เอนทิตีที่เกี่ยวข้อง | บทบาทความตั้งใจในการค้นหา |
|---|---|---|---|
| WebView | คอมโพเนนต์ UI แบบเนทีฟที่ฝังอยู่ซึ่งใช้สำหรับแสดงผลหน้าเว็บภายในแอปพลิเคชันมือถือ | WebViewClient / WKWebView |
เชิงข้อมูล / เชิงเทคนิค |
| Custom URL Scheme | คำนำหน้า URI ที่ลงทะเบียนกับแอป (เช่น myapp://) ซึ่งช่วยให้สามารถนำทางภายนอกไปยังหน้าจอเนทีฟได้ |
Intent.ACTION_VIEW |
เชิงเทคนิค / เชิงข้อมูล |
| WKNavigationDelegate | โปรโตคอล WebKit ที่อนุญาตให้แอปโฮสต์ยอมรับ ยกเลิก หรือเปลี่ยนเส้นทางกระบวนการนำทางใน WKWebView |
decidePolicyForNavigationAction |
เชิงเทคนิค |
| WKUIDelegate | โปรโตคอล WebKit ที่รับผิดชอบในการจัดการคำขอสร้างหน้าต่างใหม่ใน WKWebView |
createWebViewWith |
เชิงเทคนิค |
| WebResourceRequest | ออบเจ็กต์ Android API 24+ ที่ห่อหุ้ม URL, เฟรม, เมธอด HTTP, การเปลี่ยนเส้นทาง และข้อมูลเมตาดาต้าของท่าทางสัมผัส | shouldOverrideUrlLoading |
เชิงเทคนิค |
| WebChromeClient | อินเทอร์เฟซ callback ของ Android WebView ที่จัดการไดอะล็อก JavaScript, ความคืบหน้า และ onCreateWindow |
WebViewTransport |
เชิงเทคนิค |
| IntentSanitizer | ยูทิลิตี้ AndroidX Core ที่ใช้กรองหรือตรวจสอบความถูกต้องของฟิลด์ Intent ที่ไม่น่าเชื่อถือก่อนการส่งต่ออย่างเคร่งครัด | การป้องกันการเปลี่ยนเส้นทาง Intent | เชิงเทคนิค / ความปลอดภัย |
| Universal Links | มาตรฐาน deep-linking บน HTTPS ของ Apple ที่เชื่อมโยงโดเมนเว็บที่ตรวจสอบแล้วเข้ากับแอปพลิเคชัน iOS ที่ติดตั้งไว้ | Associated Domains | เชิงเทคนิค / เชิงข้อมูล |
| Package Visibility | การกรองของ OS บน Android 11+ (targetSdk >= 30) ที่จำกัดว่าแอปโฮสต์สามารถคิวรีแอปที่ติดตั้งใดได้บ้างผ่าน PackageManager |
แท็ก Manifest <queries> |
เชิงเทคนิค |
| Intent URI | URI ของ Android ที่มีโครงสร้าง (intent://) ซึ่งเข้ารหัสแพ็กเกจเป้าหมาย, scheme และ URL สำรองของเบราว์เซอร์ |
Intent.URI_INTENT_SCHEME |
เชิงเทคนิค |
ข้อมูลพื้นฐานความเข้ากันได้และสถานะการตรวจสอบ
-
เป้าหมายความเข้ากันได้ที่ตั้งใจไว้: Android
minSdk 24,compileSdk 34/35,targetSdk 34/35(Android 14/15), บริบทการเสริมความปลอดภัยการเปลี่ยนเส้นทาง Intent ของ Android 16 (API 36),androidx.core:core:1.9.0+(IntentSanitizer); iOS 15.0–18.0 (เปิดใช้งานisInspectableบน iOS 16.4+), Xcode 15/16, Swift 5.9/6.0 -
สถานะการตรวจสอบ:
-
การตรวจสอบ API เชิงสถิติและข้อกำหนด: ดำเนินการเสร็จสิ้นเทียบกับข้อกำหนดอย่างเป็นทางการของ Android Developers, AndroidX Core, Apple Developer, IETF RFC 3986 และ OWASP MASTG
-
การคอมไพล์และการตรวจสอบบนอุปกรณ์จริง: ยังไม่ได้ดำเนินการ ในรอบการตรวจสอบนี้ ทีมงานต้องคอมไพล์และดำเนินการทดสอบการถดถอยบนอุปกรณ์จริง ซึ่งครอบคลุมถึง URL ป๊อปอัปเริ่มต้นที่เป็นอันตราย, เชน 302 ข้ามโดเมน, ฮอป 302 ต่อเนื่อง, การสร้างหน้าต่าง iframe ของบุคคลที่สาม, Android App Links (
assetlinks.json), iOS Associated Domains (การแคช AASA), การยกเลิก Universal Link แบบอะซิงโครนัสที่ล้าสมัย, เชนสำรองintent://, และการส่งต่อActivityNotFoundExceptionก่อนที่จะเปิดใช้งานจริง (production rollout)
-
ข้อมูลอ้างอิง
Share this article



