蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Chromium WebView 线程隔离、evaluateJavascript、自定义 Scheme 与联系人修复离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-webview-attention.py
explore-tutorial-webview-attention.py160 行
"""Offline Android 4.4+ Chromium WebView threading, evaluateJavascript & custom scheme verifier (Ch 97: tutorial-webview-attention)."""
from __future__ import annotations

import json
import re
import sys
import urllib.parse

VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"


class ChromiumWebViewGuard:
    def __init__(self, ui_thread_name: str = "main"):
        self.ui_thread = ui_thread_name
        self.default_ua = (
            "Mozilla/5.0 (Linux; Android 4.4; Nexus 4 Build/KRT16H) "
            "AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36"
        )
        self.custom_ua = self.default_ua

    def call_webview_method(self, caller_thread: str, action: str) -> dict:
        if caller_thread != self.ui_thread:
            return {
                "ok": False,
                "error": f"RuntimeException: A WebView method was called on thread '{caller_thread}'. All WebView methods must be called on the same thread.",
            }
        return {"ok": True, "executed": action, "thread": caller_thread}

    def evaluate_javascript_async(self, script: str) -> dict:
        # Non-blocking async evaluation returning JSON-encoded callback value
        if script == "fn()":
            return {"blocking_ui_thread": False, "callback_value": '"ok_from_js"'}
        return {"blocking_ui_thread": False, "callback_value": "null"}

    def should_override_url(self, href: str, app_scheme: str = "example-app:") -> dict:
        # Android 4.4+ Chromium WebView only invokes shouldOverrideUrlLoading for valid URLs with a scheme
        if ":" not in href:
            return {"callback_invoked": False, "handled": False, "decoded_data": None}
        if href.startswith(app_scheme):
            raw = href[len(app_scheme) :]
            return {
                "callback_invoked": True,
                "handled": True,
                "decoded_data": urllib.parse.unquote(raw),
            }
        return {"callback_invoked": True, "handled": False, "decoded_data": None}


def main() -> None:
    wv = ChromiumWebViewGuard()
    cases = []

    # Case 1: Thread confinement (JavaBridge worker thread violation vs runOnUiThread/post fix)
    bad_call = wv.call_webview_method("JavaBridge", "loadUrl('javascript:show(...)')")
    good_call = wv.call_webview_method("main", "loadUrl('javascript:show(...)')")
    actual1 = {
        "worker_thread_rejected": not bad_call["ok"],
        "mentions_same_thread_rule": "same thread" in bad_call["error"],
        "ui_thread_accepted": good_call["ok"],
    }
    expected1 = {
        "worker_thread_rejected": True,
        "mentions_same_thread_rule": True,
        "ui_thread_accepted": True,
    }
    cases.append({
        "name": "webview_ui_thread_confinement",
        "summary": "Verify Chromium WebView rejects JavaBridge thread calls and succeeds when dispatched to UI thread.",
        "expected": expected1,
        "actual": actual1,
        "passed": actual1 == expected1,
    })

    # Case 2: evaluateJavascript async callback vs UI thread blocking anti-pattern
    eval_res = wv.evaluate_javascript_async("fn()")
    actual2 = {
        "async_non_blocking": not eval_res["blocking_ui_thread"],
        "decoded_value": json.loads(eval_res["callback_value"]),
    }
    expected2 = {"async_non_blocking": True, "decoded_value": "ok_from_js"}
    cases.append({
        "name": "evaluate_javascript_async_callback",
        "summary": "Verify API 19+ evaluateJavascript non-blocking ValueCallback result decoding.",
        "expected": expected2,
        "actual": actual2,
        "passed": actual2 == expected2,
    })

    # Case 3: Custom URL scheme validation in shouldOverrideUrlLoading
    bare_rel = wv.should_override_url("showProfile")
    valid_custom = wv.should_override_url("example-app:showProfile%2F42")
    normal_http = wv.should_override_url("https://example.org/help")
    actual3 = {
        "bare_relative_ignored": not bare_rel["callback_invoked"],
        "custom_scheme_handled": valid_custom["handled"],
        "custom_scheme_decoded": valid_custom["decoded_data"],
        "http_passed_to_webview": normal_http["callback_invoked"] and not normal_http["handled"],
    }
    expected3 = {
        "bare_relative_ignored": True,
        "custom_scheme_handled": True,
        "custom_scheme_decoded": "showProfile/42",
        "http_passed_to_webview": True,
    }
    cases.append({
        "name": "custom_url_scheme_validation",
        "summary": "Verify Android 4.4+ Chromium WebView ignores schemeless relative href in shouldOverrideUrlLoading and decodes example-app: scheme.",
        "expected": expected3,
        "actual": actual3,
        "passed": actual3 == expected3,
    })

    # Case 4: Chromium User-Agent token detection & custom User-Agent override
    chrome_match = re.search(r"Chrome/([\d.]+)", wv.default_ua)
    wv.custom_ua = wv.default_ua + " MyHybridApp/2.1"
    actual4 = {
        "chrome_version": chrome_match.group(1) if chrome_match else "",
        "custom_ua_has_app_token": "MyHybridApp/2.1" in wv.custom_ua,
    }
    expected4 = {"chrome_version": "30.0.0.0", "custom_ua_has_app_token": True}
    cases.append({
        "name": "chromium_user_agent_and_override",
        "summary": "Verify Chromium WebView default User-Agent Chrome/30.0.0.0 token and setUserAgentString customization.",
        "expected": expected4,
        "actual": actual4,
        "passed": actual4 == expected4,
    })

    # Case 5: Combined fix for Ch 96 Nexus 5 contacts issue (@JavascriptInterface + runOnUiThread/post)
    def run_contacts_bridge(has_annotation: bool, posted_to_ui: bool) -> str:
        if not has_annotation:
            return "FAIL_NOT_EXPOSED_API17_PLUS"
        if not posted_to_ui:
            return "FAIL_WRONG_THREAD_JAVABRIDGE"
        return "SUCCESS_CONTACTS_RENDERED"

    actual5 = {
        "no_annotation": run_contacts_bridge(False, False),
        "annotated_only": run_contacts_bridge(True, False),
        "annotated_and_ui_post": run_contacts_bridge(True, True),
    }
    expected5 = {
        "no_annotation": "FAIL_NOT_EXPOSED_API17_PLUS",
        "annotated_only": "FAIL_WRONG_THREAD_JAVABRIDGE",
        "annotated_and_ui_post": "SUCCESS_CONTACTS_RENDERED",
    }
    cases.append({
        "name": "nexus5_contacts_bridge_combined_fix",
        "summary": "Verify fixing Ch 96 contacts WebView requires both @JavascriptInterface and dispatching loadUrl/evaluateJavascript to the UI thread.",
        "expected": expected5,
        "actual": actual5,
        "passed": actual5 == expected5,
    })

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    sys.exit(main())
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-webview-attention-lab/explore-tutorial-webview-attention.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-webview-attention.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1973.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习