### Create Custom WebSettings in AgentWeb Source: https://github.com/justson/agentweb/wiki/WebSettings-自定义设置 This example shows how to create a custom `WebSettings` class by extending `WebDefaultSettingsManager` and overriding the `toSetting` method. This allows for fine-grained control over specific settings like file access and network image blocking. ```java public class CustomSettings extends WebDefaultSettingsManager { protected CustomSettings() { super(); } @Override public AgentWebSettings toSetting(WebView webView) { super.toSetting(webView); getWebSettings().setBlockNetworkImage(false);//是否阻塞加载网络图片 协议http or https getWebSettings().setAllowFileAccess(false); //允许加载本地文件html file协议, 这可能会造成不安全 , 建议重写关闭 getWebSettings().setAllowFileAccessFromFileURLs(false); //通过 file url 加载的 Javascript 读取其他的本地文件 .建议关闭 getWebSettings().setAllowUniversalAccessFromFileURLs(false);//允许通过 file url 加载的 Javascript 可以访问其他的源,包括其他的文件和 http,https 等其他的源 return this; } } ``` -------------------------------- ### Get WebView Instance Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Retrieve the underlying `WebView` instance managed by AgentWeb. ```java mAgentWeb.getWebCreator().getWebView(); ``` -------------------------------- ### Preview Image Before Upload with JavaScript Source: https://github.com/justson/agentweb/blob/androidx/sample/src/main/assets/upload_file/jsuploadfile.html Displays a selected local image in an HTML element before it is uploaded. It uses the `getFileUrl` function to get the image source. ```javascript function preImg(sourceId, targetId) { document.getElementById("uploadFile") var url = getFileUrl(sourceId); console.log(url); var imgPre = document.getElementById(targetId); imgPre.src = url; } ``` -------------------------------- ### AgentWeb.with() - Basic Initialization and Loading Source: https://context7.com/justson/agentweb/llms.txt Demonstrates the fundamental usage of AgentWeb to initialize and load a URL within an Activity or Fragment. It shows how to set up the parent container, optional clients, security type, and initiate the page load. ```APIDOC ## AgentWeb.with() - Basic Initialization and Loading `AgentWeb.with(activity/fragment)` is the entry point for the library. Use the chained Builder API to create and load pages in a WebView. `setAgentWebParent` specifies the container (not ConstraintLayout), `.ready()` initializes the WebView, and `.go(url)` starts loading the page. ### Activity Usage Example ```java private AgentWeb mAgentWeb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout container = findViewById(R.id.web_container); mAgentWeb = AgentWeb.with(this) .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator() // Use default blue progress bar .setWebChromeClient(mWebChromeClient) // Optional: Custom ChromeClient .setWebViewClient(mWebViewClient) // Optional: Custom ViewClient .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) // Strict security mode .createAgentWeb() .ready() .go("https://www.example.com"); } ``` ### Fragment Usage Example ```java mAgentWeb = AgentWeb.with(this /* Fragment */) .setAgentWebParent((ViewGroup) view, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator(Color.RED, 3) // Custom color and height (dp) .createAgentWeb() .ready() .go("https://www.example.com"); ``` ``` -------------------------------- ### Configure WebChromeClient and WebViewClient Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Initialize AgentWeb with custom `WebChromeClient` and `WebViewClient` for handling page loading progress, titles, and other events. ```java AgentWeb.with(this) .setAgentWebParent(mLinearLayout,new LinearLayout.LayoutParams(-1,-1) ) .useDefaultIndicator() .setReceivedTitleCallback(mCallback) .setWebChromeClient(mWebChromeClient) .setWebViewClient(mWebViewClient) .setSecutityType(AgentWeb.SecurityType.strict) .createAgentWeb() .ready() .go(getUrl()); ``` ```java private WebViewClient mWebViewClient=new WebViewClient(){ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { //do you work } }; ``` ```java private WebChromeClient mWebChromeClient=new WebChromeClient(){ @Override public void onProgressChanged(WebView view, int newProgress) { //do you work } }; ``` -------------------------------- ### Basic AgentWeb WebView Initialization and Loading Source: https://context7.com/justson/agentweb/llms.txt Initialize AgentWeb using AgentWeb.with() and chain configuration methods. Use setAgentWebParent to specify the container and go() to load a URL. Supports Activity and Fragment contexts. ```java // Basic usage in Activity private AgentWeb mAgentWeb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout container = findViewById(R.id.web_container); mAgentWeb = AgentWeb.with(this) .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator() // Use default progress bar (blue) .setWebChromeClient(mWebChromeClient) // Optional: Custom ChromeClient .setWebViewClient(mWebViewClient) // Optional: Custom ViewClient .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) // Strict security mode .createAgentWeb() .ready() .go("https://www.example.com"); } // Usage in Fragment mAgentWeb = AgentWeb.with(this /* Fragment */) .setAgentWebParent((ViewGroup) view, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator(Color.RED, 3) // Custom color and height (dp) .createAgentWeb() .ready() .go("https://www.example.com"); ``` -------------------------------- ### Get Local File URL (JavaScript) Source: https://github.com/justson/agentweb/blob/androidx/sample/src/main/assets/upload_file/uploadfile.html Retrieves the local URL of a file selected through an input field. It includes logic to handle different browser types like IE, Firefox, and Chrome. ```javascript function getFileUrl(sourceId) { var url; console.log(navigator.userAgent); if (navigator.userAgent.indexOf("MSIE") >= 1) { // IE url = document.getElementById(sourceId).value; } else if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } return url; } ``` -------------------------------- ### Initialize AgentWeb Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Basic initialization of AgentWeb with a parent view and default indicator. Navigates to a specified URL. ```java mAgentWeb = AgentWeb.with(this) .setAgentWebParent((LinearLayout) view, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator() .createAgentWeb() .ready() .go("http://www.jd.com"); ``` -------------------------------- ### Initialize AgentWeb with Default Settings Source: https://github.com/justson/agentweb/wiki/AgentWeb-视图结构 Initializes AgentWeb with a parent layout, default progress bar, and a callback for page titles. It then navigates to a specified URL. ```java AgentWeb.with(this)//传入Activity .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ,如果父控件为 RelativeLayout , 那么第二参数需要传入 RelativeLayout.LayoutParams .useDefaultIndicator()// 使用默认进度条 .defaultProgressBarColor() // 使用默认进度条颜色 .setReceivedTitleCallback(mCallback) //设置 Web 页面的 title 回调 .createAgentWeb() .ready() .go("http://www.jd.com"); ``` -------------------------------- ### Registering Multiple Middlewares in AgentWeb Source: https://context7.com/justson/agentweb/llms.txt Demonstrates how to register custom WebViewClient and WebChromeClient middlewares in sequence using AgentWeb's builder pattern. Middlewares are executed in the order they are registered. ```java mAgentWeb = AgentWeb.with(this) .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator() .useMiddlewareWebClient(new UrlInterceptMiddleware()) .useMiddlewareWebChrome(new TitleTrackMiddleware()) .createAgentWeb().ready().go(url); ``` -------------------------------- ### Java to JavaScript Communication with AgentWeb Source: https://context7.com/justson/agentweb/llms.txt Utilize getJsAccessEntrace() for calling JavaScript methods. quickCallJs() simplifies parameter handling, while callJs() supports asynchronous calls with return values. Both methods ensure execution on the main thread. ```java // JavaScript function defined on the JS side // function showToast(msg) { alert(msg); } // function getPageTitle() { return document.title; } // 1. Call without parameters mAgentWeb.getJsAccessEntrace().quickCallJs("showToast", "Hello from Android"); // 2. Call with multiple parameters mAgentWeb.getJsAccessEntrace().quickCallJs("login", "user@example.com", "password123"); // 3. Asynchronous call with return value (callJs accepts a complete JS expression) mAgentWeb.getJsAccessEntrace().callJs("getPageTitle()", new ValueCallback() { @Override public void onReceiveValue(String value) { // value = "\"My Page Title\"" (in JSON string format) Log.d("AgentWeb", "Page title: " + value); runOnUiThread(() -> tvTitle.setText(value)); } }); ``` -------------------------------- ### Configure for Fullscreen Video Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Add necessary configurations to the AndroidManifest.xml for proper fullscreen video playback within AgentWeb. ```xml android:hardwareAccelerated="true" android:configChanges="orientation|screenSize" ``` -------------------------------- ### handleKeyEvent() / back() - Back Key Handling Source: https://context7.com/justson/agentweb/llms.txt Methods for handling the back key press. `handleKeyEvent()` forwards the event to AgentWeb for processing (e.g., exiting full-screen video), while `back()` navigates back through the WebView's history. ```APIDOC ## handleKeyEvent() / back() - Back Key Handling `handleKeyEvent()` forwards `KeyEvent` to AgentWeb for handling. `back()` attempts to navigate back in the WebView's history. If there are no previous pages, it returns `false`, allowing the host to handle it (e.g., close the Activity). ### Handling KeyEvent in Activity ```java @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Prioritize AgentWeb handling for back events (e.g., video full screen) if (mAgentWeb.handleKeyEvent(keyCode, event)) { return true; } return super.onKeyDown(keyCode, event); } ``` ### Using back() for Custom Back Button ```java // Or use back() when a custom back button is clicked binding.btnBack.setOnClickListener(v -> { if (!mAgentWeb.back()) { // WebView has no history, close the current page finish(); } }); ``` ``` -------------------------------- ### AgentWeb Core Dependencies (AndroidX) Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Use these AndroidX compatible versions for the core AgentWeb library, file chooser, and downloader if your project uses AndroidX. ```groovy implementation 'com.github.Justson.AgentWeb:agentweb-core:v5.0.0-alpha.1-androidx' // (必选) implementation 'com.github.Justson.AgentWeb:agentweb-filechooser:v5.0.0-alpha.1-androidx' // (可选) implementation 'com.github.Justson:Downloader:v5.0.0-androidx' // (可选) ``` -------------------------------- ### Handle Key Events Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Implement `onKeyDown` to allow AgentWeb to handle key events, such as back navigation within the WebView. ```java @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mAgentWeb.handleKeyEvent(keyCode, event)) { return true; } return super.onKeyDown(keyCode, event); } ``` -------------------------------- ### Add AgentWeb Dependencies to Project Source: https://context7.com/justson/agentweb/llms.txt Include AgentWeb and optional modules in your project's build.gradle files. Ensure mavenCentral and jitpack.io are added to your root project's repositories. ```groovy // Project root build.gradle allprojects { repositories { mavenCentral() maven { url 'https://jitpack.io' } } } // Module build.gradle dependencies { implementation 'io.github.justson:agentweb-core:v5.1.1-androidx' // Required implementation 'io.github.justson:agentweb-filechooser:v5.1.1-androidx' // Optional: File chooser implementation 'com.github.Justson:Downloader:v5.0.4-androidx' // Optional: File downloader } ``` -------------------------------- ### Call Javascript from Java using AgentWeb Source: https://github.com/justson/agentweb/wiki/Java-与-Javascript-通信 Use quickCallJs to invoke a Javascript function from Java. Provide the Javascript function name and its arguments. ```javascript //Js 方法 function callByAndroid(name){ console.log("callByAndroid:"+name) } ``` ```java //Android 端 mAgentWeb.getJsEntraceAccess().quickCallJs("callByAndroid","AgentWeb"); //第一个参数为方法名, 第二个参数为Js方法的入参 //结果 consoleMessage:callByAndroid:AgentWeb ``` -------------------------------- ### Apply Default WebSettings in AgentWeb Source: https://github.com/justson/agentweb/wiki/WebSettings-自定义设置 This snippet shows the default configuration applied to WebSettings by AgentWeb, including network cache modes, mixed content handling, and various other WebView behaviors. It's essential for understanding the baseline settings before customization. ```java mWebSettings = webView.getSettings(); mWebSettings.setJavaScriptEnabled(true); mWebSettings.setSupportZoom(true); mWebSettings.setBuiltInZoomControls(false); mWebSettings.setSavePassword(false); if (AgentWebUtils.checkNetwork(webView.getContext())) { //根据cache-control获取数据。 mWebSettings.setCacheMode(android.webkit.WebSettings.LOAD_DEFAULT); } else { //没网,则从本地获取,即离线加载 mWebSettings.setCacheMode(android.webkit.WebSettings.LOAD_CACHE_ELSE_NETWORK); } if (Build.VERSION.SDK_INT >= 21) { //适配5.0不允许http和https混合使用情况 mWebSettings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); webView.setLayerType(View.LAYER_TYPE_HARDWARE, null); } else if (Build.VERSION.SDK_INT >= 19) { webView.setLayerType(View.LAYER_TYPE_HARDWARE, null); } else if (Build.VERSION.SDK_INT < 19) { webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } // mWebSettings.setRenderPriority(android.webkit.AgentWebSettings.RenderPriority.HIGH); mWebSettings.setTextZoom(100); mWebSettings.setDatabaseEnabled(true); mWebSettings.setAppCacheEnabled(true); mWebSettings.setLoadsImagesAutomatically(true); mWebSettings.setSupportMultipleWindows(false); mWebSettings.setBlockNetworkImage(false);//是否阻塞加载网络图片 协议http or https mWebSettings.setAllowFileAccess(true); //允许加载本地文件html file协议, 这可能会造成不安全 , 建议重写关闭 mWebSettings.setAllowFileAccessFromFileURLs(false); //通过 file url 加载的 Javascript 读取其他的本地文件 .建议关闭 mWebSettings.setAllowUniversalAccessFromFileURLs(false);//允许通过 file url 加载的 Javascript 可以访问其他的源,包括其他的文件和 http,https 等其他的源 mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true); if (Build.VERSION.SDK_INT >=19) mWebSettings.setLayoutAlgorithm(android.webkit.WebSettings.LayoutAlgorithm.SINGLE_COLUMN); else mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); mWebSettings.setLoadWithOverviewMode(true); mWebSettings.setUseWideViewPort(true); mWebSettings.setDomStorageEnabled(true); mWebSettings.setNeedInitialFocus(true); mWebSettings.setDefaultTextEncodingName("utf-8");//设置编码格式 mWebSettings.setDefaultFontSize(16); mWebSettings.setMinimumFontSize(12);//设置 WebView 支持的最小字体大小,默认为 8 mWebSettings.setGeolocationEnabled(true); // String dir = AgentWebConfig.getCachePath(webView.getContext()); LogUtils.i(TAG, "dir:" + dir + " appcache:" + AgentWebConfig.getCachePath(webView.getContext())); //设置数据库路径 api19 已经废弃,这里只针对 webkit 起作用 mWebSettings.setGeolocationDatabasePath(dir); mWebSettings.setDatabasePath(dir); mWebSettings.setAppCachePath(dir); //缓存文件最大值 mWebSettings.setAppCacheMaxSize(Long.MAX_VALUE); ``` -------------------------------- ### AgentWebCompat.setDataDirectorySuffix() Source: https://context7.com/justson/agentweb/llms.txt Resolves the `Using WebView from more than one process` crash issue in multi-process applications. This method must be called during the process initialization phase. ```APIDOC ## AgentWebCompat.setDataDirectorySuffix() ### Description Resolves the `Using WebView from more than one process` crash issue in multi-process applications. This method must be called during the process initialization phase (earliest in `Application.onCreate` or `Activity.onCreate`). ### Method `AgentWebCompat.setDataDirectorySuffix(Context context)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // Fix multi-process WebView crash, must be called before WebView initialization AgentWebCompat.setDataDirectorySuffix(this); } } // Declare multi-process Activity in AndroidManifest.xml // ``` ### Response None explicitly documented. ``` -------------------------------- ### AgentWebConfig - Cookie and Cache Management Source: https://context7.com/justson/agentweb/llms.txt Utilize static methods in AgentWebConfig for comprehensive Cookie management (reading, injecting, syncing, clearing) and disk cache operations. ```APIDOC ## AgentWebConfig — Cookie Management and Cache Clearing `AgentWebConfig` provides static utility methods for reading, injecting, syncing, and clearing Cookies, as well as managing disk cache, with compatibility for Android 4.4+. ```java // Read Cookies for a specific URL String cookies = AgentWebConfig.getCookiesByUrl("https://www.example.com"); Log.d("Cookie", cookies); // Output: "sessionId=abc123; userId=456" // Inject Cookies (call before loading) AgentWebConfig.syncCookie("https://www.example.com", "token=Bearer_xyz789"); AgentWebConfig.syncCookie("https://www.example.com", "userId=123456"); // Remove Session Cookies (use during logout) AgentWebConfig.removeSessionCookies(value -> { Log.d("Cookie", "Session cookies cleared: " + value); }); // Remove all Cookies AgentWebConfig.removeAllCookies(value -> { Log.d("Cookie", "All cookies cleared: " + value); }); // Clear disk cache (can be offered to users in settings) AgentWebConfig.clearDiskCache(context); Log.d("Cache", "WebView disk cache cleared, path: " + AgentWebConfig.getCachePath(context)); // Enable Debug mode (also enables WebView remote debugging) AgentWebConfig.debug(); ``` ``` -------------------------------- ### Enable Multi-Process WebView Compatibility with setDataDirectorySuffix() Source: https://context7.com/justson/agentweb/llms.txt Resolves the 'Using WebView from more than one process' crash in multi-process applications. Must be called early in process initialization. ```java public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // 修复多进程 WebView 崩溃,需在 WebView 初始化前调用 AgentWebCompat.setDataDirectorySuffix(this); } } ``` ```xml // AndroidManifest.xml 中声明多进程 Activity // ``` -------------------------------- ### useDefaultIndicator() / setCustomIndicator() — 进度条配置 Source: https://context7.com/justson/agentweb/llms.txt Configure the progress bar for AgentWeb. Options include using the default style, customizing color and height, or providing a completely custom progress bar view, as well as disabling the progress bar. ```APIDOC ## Progress Bar Configuration ### Description AgentWeb's built-in progress bar is based on `BaseIndicatorView`. You can use the default style, customize its color and height, or implement your own progress bar view. It's also possible to disable the progress bar entirely. ### Options **1. Use Default Progress Bar (Default Blue):** ```java .useDefaultIndicator() ``` **2. Customize Color and Height (in dp):** ```java .useDefaultIndicator(Color.parseColor("#FF5722"), 4) ``` **3. Completely Disable Progress Bar:** ```java .closeIndicator() ``` **4. Use Custom View (Inheriting `BaseIndicatorView`):** ```java public class MyIndicatorView extends BaseIndicatorView { public MyIndicatorView(Context context) { super(context); } @Override public void show() { setVisibility(VISIBLE); } @Override public void hide() { setVisibility(GONE); } @Override public void offerLayoutParams() { setLayoutParams(new FrameLayout.LayoutParams(-1, AgentWebUtils.dp2px(getContext(), 3))); } @Override public void setProgress(int newProgress) { // Update custom progress animation } } // In the Builder: .setCustomIndicator(new MyIndicatorView(this)) ``` ``` -------------------------------- ### AgentWeb Core Dependencies Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Add the core AgentWeb library and optional components like the file chooser and downloader to your app's build.gradle file. ```groovy implementation 'com.github.Justson.AgentWeb:agentweb-core:v5.0.0-alpha' // (必选) implementation 'com.github.Justson.AgentWeb:agentweb-filechooser:v5.0.0-alpha' // (可选) implementation 'com.github.Justson:Downloader:v5.0.0' // (可选) ``` -------------------------------- ### Manage WebView Lifecycle Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Integrate AgentWeb's lifecycle methods (`onPause`, `onResume`, `onDestroy`) with the Activity or Fragment lifecycle to save resources. ```java @Override protected void onPause() { mAgentWeb.getWebLifeCycle().onPause(); super.onPause(); } ``` ```java @Override protected void onResume() { mAgentWeb.getWebLifeCycle().onResume(); super.onResume(); } ``` ```java @Override public void onDestroyView() { mAgentWeb.getWebLifeCycle().onDestroy(); super.onDestroyView(); } ``` -------------------------------- ### Add AgentWeb Gradle Dependencies Source: https://github.com/justson/agentweb/blob/androidx/README.md Include these dependencies in your project's build.gradle file to use AgentWeb. The core library is required, while filechooser and Downloader are optional. ```groovy allprojects { repositories { mavenCentral() maven { url 'https://jitpack.io' } } } ``` ```groovy implementation 'io.github.justson:agentweb-core:v5.1.1-androidx' implementation 'io.github.justson:agentweb-filechooser:v5.1.1-androidx' // (可选) implementation 'com.github.Justson:Downloader:v5.0.4-androidx' // (可选) ``` -------------------------------- ### WebLifeCycle - Lifecycle Management Source: https://context7.com/justson/agentweb/llms.txt Provides methods to manage the WebView's lifecycle, ensuring proper resource release and rendering control. These methods should be called in the corresponding Activity/Fragment lifecycle callbacks. ```APIDOC ## WebLifeCycle - Lifecycle Management `getWebLifeCycle()` returns the WebView lifecycle management object. Call its methods within your Activity/Fragment lifecycle callbacks to correctly release CPU resources, pause/resume rendering, and prevent memory leaks. ### onResume() ```java @Override protected void onResume() { mAgentWeb.getWebLifeCycle().onResume(); super.onResume(); } ``` ### onPause() ```java @Override protected void onPause() { mAgentWeb.getWebLifeCycle().onPause(); // Pause all WebViews in the application super.onPause(); } ``` ### onDestroy() ```java @Override protected void onDestroy() { mAgentWeb.getWebLifeCycle().onDestroy(); // Destroy WebView and release resources super.onDestroy(); } ``` ``` -------------------------------- ### Call JavaScript from Android Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Demonstrates how to call a JavaScript function defined in the WebView from the Android side using quickCallJs. ```javascript function callByAndroid(){ console.log("callByAndroid") } ``` ```java mAgentWeb.getJsAccessEntrace().quickCallJs("callByAndroid"); ``` -------------------------------- ### Handle Back Key Events with AgentWeb Source: https://context7.com/justson/agentweb/llms.txt Use handleKeyEvent() to forward KeyEvent to AgentWeb for processing, especially for scenarios like full-screen video. Use back() to navigate back through WebView history; it returns false if there's no history, allowing the host to handle it (e.g., close Activity). ```java @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Prioritize AgentWeb handling of back events (e.g., video fullscreen) if (mAgentWeb.handleKeyEvent(keyCode, event)) { return true; } return super.onKeyDown(keyCode, event); } // Or use back() in a custom back button click listener binding.btnBack.setOnClickListener(v -> { if (!mAgentWeb.back()) { // WebView has no history, close the current page finish(); } }); ``` -------------------------------- ### Middleware WebClient and WebChrome Source: https://context7.com/justson/agentweb/llms.txt Implement custom WebViewClient and WebChromeClient middleware to intercept and process web requests and page events in a chainable manner. ```APIDOC ## useMiddlewareWebClient() / useMiddlewareWebChrome() AgentWeb supports a middleware chain based on the onion model, allowing multiple `MiddlewareWebClientBase` and `MiddlewareWebChromeBase` to be registered. Each middleware only needs to override methods it's interested in. Requests flow sequentially according to the registration order, eventually reaching AgentWeb's built-in default implementation. ```java // Custom WebViewClient middleware: Intercept specific URL loading public class UrlInterceptMiddleware extends MiddlewareWebClientBase { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { String url = request.getUrl().toString(); if (url.startsWith("myapp://")) { // Handle custom scheme, prevent WebView from continuing to load handleDeepLink(url); return true; } // Pass to the next middleware or default implementation return super.shouldOverrideUrlLoading(view, request); } private void handleDeepLink(String url) { Log.d("Middleware", "Deep link intercepted: " + url); } } // Custom WebChromeClient middleware: Track page title changes public class TitleTrackMiddleware extends MiddlewareWebChromeBase { @Override public void onReceivedTitle(WebView view, String title) { Log.d("Middleware", "Page title changed: " + title); // EventBus.getDefault().post(new TitleChangeEvent(title)); super.onReceivedTitle(view, title); // Continue passing } } // Register multiple middlewares (executed in order) mAgentWeb = AgentWeb.with(this) .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator() .useMiddlewareWebClient(new UrlInterceptMiddleware()) .useMiddlewareWebChrome(new TitleTrackMiddleware()) .createAgentWeb().ready().go(url); ``` ``` -------------------------------- ### JavaScript Calling Java Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Shows how to expose Java objects to JavaScript, allowing JavaScript to call Java methods. ```java mAgentWeb.getJsInterfaceHolder().addJavaObject("android",new AndroidInterface(mAgentWeb,this)); window.android.callAndroid(); ``` -------------------------------- ### getJsAccessEntrace() - Java Calling JavaScript Source: https://context7.com/justson/agentweb/llms.txt Provides methods to invoke JavaScript functions from Java. `quickCallJs` handles simple calls, while `callJs` supports asynchronous calls with callbacks for retrieving results. ```APIDOC ## getJsAccessEntrace() - Java Calling JavaScript `getJsAccessEntrace()` encapsulates calls to JavaScript methods. `quickCallJs(methodName, args...)` automatically handles parameter concatenation. `callJs(jsCode, callback)` supports asynchronous calls with return values and includes main thread switching protection. ### JavaScript Functions (Example) ```javascript // JS function defined on the page // function showToast(msg) { alert(msg); } // function getPageTitle() { return document.title; } ``` ### 1. Calling a JavaScript function without parameters ```java // 1. No parameter call mAgentWeb.getJsAccessEntrace().quickCallJs("showToast", "Hello from Android"); ``` ### 2. Calling a JavaScript function with multiple parameters ```java // 2. Multiple parameter call mAgentWeb.getJsAccessEntrace().quickCallJs("login", "user@example.com", "password123"); ``` ### 3. Calling a JavaScript function with a callback for results ```java // 3. Asynchronous call with return value (callJs accepts a complete JS expression) mAgentWeb.getJsAccessEntrace().callJs("getPageTitle()", new ValueCallback() { @Override public void onReceiveValue(String value) { // value = "\"My Page Title\"" (in JSON string format) Log.d("AgentWeb", "Page Title: " + value); runOnUiThread(() -> tvTitle.setText(value)); } }); ``` ``` -------------------------------- ### Configuring External App Jump Strategy with OpenOtherPageWays Source: https://context7.com/justson/agentweb/llms.txt Control how AgentWeb handles URLs that should open external applications using the OpenOtherPageWays enum. Options include direct jumps, user confirmation prompts, or disallowing jumps. ```java mAgentWeb = AgentWeb.with(this) .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator() .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK) // 弹窗询问 .isInterceptUnkownUrl(true) // 拦截无法处理的 URL(默认 true) .createAgentWeb().ready() .go("https://payment.example.com/checkout"); // 微信支付:AgentWeb 自动拦截 weixin://wap/pay? 并调起微信,无需额外配置 // 支付宝支付:需在 build.gradle 中额外依赖支付宝 SDK // implementation files('libs/alipaySdk-xxx.jar') ``` -------------------------------- ### Customize WebView Settings in AgentWeb Source: https://context7.com/justson/agentweb/llms.txt Customize WebView settings by extending AbsAgentWebSettings or directly modifying the WebSettings object. Recommended for applying custom configurations during the Builder phase. ```java // 方式一:直接获取 WebSettings 修改 mAgentWeb.getAgentWebSettings().getWebSettings().setUserAgentString("MyApp/1.0 AgentWeb"); ``` ```java // 方式二:自定义 Settings 类(推荐,在 Builder 阶段注入) public class SecureWebSettings extends AbsAgentWebSettings { @Override public IAgentWebSettings toSetting(WebView webView) { super.toSetting(webView); // 应用 AgentWeb 默认配置 WebSettings settings = getWebSettings(); // 增强安全配置 settings.setAllowFileAccess(false); settings.setAllowFileAccessFromFileURLs(false); settings.setAllowUniversalAccessFromFileURLs(false); // 自定义 UA settings.setUserAgentString( settings.getUserAgentString() + " MyApp/2.0" ); // 强制离线缓存(例如在无网络时) settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); return this; } } ``` ```java // 在 Builder 中注入 mAgentWeb = AgentWeb.with(this) .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator() .setAgentWebWebSettings(new SecureWebSettings()) .createAgentWeb().ready().go(url); ``` -------------------------------- ### Handle File Upload Click Event and Native Interaction Source: https://github.com/justson/agentweb/blob/androidx/sample/src/main/assets/upload_file/jsuploadfile.html Attaches a click event listener to a file upload input. If `window.agentWeb` is available, it calls its `uploadFile` method; otherwise, it alerts the type of `window.agentWeb`. ```javascript bindEvent(window, 'load', function() { var ip = document.getElementById("file_upload"); bindEvent(ip, 'click', function(e) { // alert("我是" + this + "元素, 你点击了我!"); // alert("Js 调 Android 方法成功"); if (window.agentWeb != null && typeof(window.agentWeb) != "undefined") { window.agentWeb.uploadFile(); } else { alert(typeof(window.agentWeb)); } }); }); ``` -------------------------------- ### Navigate Back Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Handle back navigation within the WebView. If AgentWeb cannot go back, it finishes the current Activity. ```java if (!mAgentWeb.back()){ AgentWebFragment.this.getActivity().finish(); } ``` -------------------------------- ### Add JitPack Repository to Gradle Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Include the JitPack repository in your project's Gradle files to fetch AgentWeb dependencies. ```groovy allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` -------------------------------- ### Dependencies Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Specifies the AgentWeb library dependencies for Android projects. ```gradle compile "com.android.support:design:${SUPPORT_LIB_VERSION}" // (3.0.0开始该库可选) compile "com.android.support:support-v4:${SUPPORT_LIB_VERSION}" SUPPORT_LIB_VERSION=27.0.2(该值会更新) ``` -------------------------------- ### PermissionInterceptor for System Permission Handling Source: https://context7.com/justson/agentweb/llms.txt Implement PermissionInterceptor to intercept system permission requests (e.g., camera, location) before they are shown to the user. This allows for conditional permission granting based on URL or other logic. ```java PermissionInterceptor mPermissionInterceptor = new PermissionInterceptor() { @Override public boolean intercept(String url, String[] permissions, String action) { Log.d("Permission", "URL: " + url + " 请求权限: " + Arrays.toString(permissions)); // 只允许可信域名获取定位权限 if (url.startsWith("https://trusted.example.com")) { return false; // 不拦截,允许系统权限弹框 } // 拒绝第三方页面的摄像头权限 for (String p : permissions) { if (p.equals(Manifest.permission.CAMERA)) { Toast.makeText(context, "不允许访问摄像头", Toast.LENGTH_SHORT).show(); return true; // 拦截,阻止系统弹框 } } return false; } }; mAgentWeb = AgentWeb.with(this) .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator() .setPermissionInterceptor(mPermissionInterceptor) .createAgentWeb().ready().go(url); ``` -------------------------------- ### Implement DownLoadResultListener for File Downloads Source: https://github.com/justson/agentweb/wiki/文件下载 Implement this listener to receive callbacks for file download success or failure. The callbacks are triggered when AgentWeb creates a download task because the file does not exist. ```java protected DownLoadResultListener mDownLoadResultListener = new DownLoadResultListener() { @Override public void success(String path) { //do you work } @Override public void error(String path, String resUrl, String cause, Throwable e) { //do you work } }; ``` -------------------------------- ### Configure Progress Bar in AgentWeb Source: https://context7.com/justson/agentweb/llms.txt Configure the WebView progress bar using default styles, custom colors/height, or by providing a completely custom view. The progress bar can also be disabled. ```java // 1. 使用默认进度条(默认蓝色) .useDefaultIndicator() ``` ```java // 2. 自定义颜色和高度(单位:dp) .useDefaultIndicator(Color.parseColor("#FF5722"), 4) ``` ```java // 3. 完全关闭进度条 .closeIndicator() ``` ```java // 4. 使用自定义 View(继承 BaseIndicatorView) public class MyIndicatorView extends BaseIndicatorView { public MyIndicatorView(Context context) { super(context); } @Override public void show() { setVisibility(VISIBLE); } @Override public void hide() { setVisibility(GONE); } @Override public void offerLayoutParams() { setLayoutParams(new FrameLayout.LayoutParams(-1, AgentWebUtils.dp2px(getContext(), 3))); } @Override public void setProgress(int newProgress) { // 更新自定义进度动画 } } .setCustomIndicator(new MyIndicatorView(this)) ``` -------------------------------- ### AgentWebConfig: Cookie Management and Cache Clearing Source: https://context7.com/justson/agentweb/llms.txt Utilize AgentWebConfig for managing cookies (reading, injecting, removing) and clearing disk cache. These static methods provide convenient access to WebView storage operations. ```java // 读取指定 URL 的 Cookie String cookies = AgentWebConfig.getCookiesByUrl("https://www.example.com"); Log.d("Cookie", cookies); // 输出: "sessionId=abc123; userId=456" // 注入 Cookie(在加载前调用) AgentWebConfig.syncCookie("https://www.example.com", "token=Bearer_xyz789"); AgentWebConfig.syncCookie("https://www.example.com", "userId=123456"); // 删除 Session Cookies(退出登录时使用) AgentWebConfig.removeSessionCookies(value -> { Log.d("Cookie", "Session cookies 已清除: " + value); }); // 删除所有 Cookies AgentWebConfig.removeAllCookies(value -> { Log.d("Cookie", "所有 cookies 已清除: " + value); }); // 清理磁盘缓存(可在设置页面提供给用户) AgentWebConfig.clearDiskCache(context); Log.d("Cache", "WebView 磁盘缓存已清理,路径:" + AgentWebConfig.getCachePath(context)); // 开启 Debug 模式(同时开启 WebView 远程调试) AgentWebConfig.debug(); ``` -------------------------------- ### AgentWeb View Layout Structure Source: https://github.com/justson/agentweb/wiki/AgentWeb-视图结构 Defines the basic layout for an AgentWeb view, including a FrameLayout to contain the WebView and a BaseIndicatorView for progress indication. ```xml ``` -------------------------------- ### Open Other Page Ways Source: https://context7.com/justson/agentweb/llms.txt Configure the behavior strategy for handling URLs that trigger external app navigation using OpenOtherPageWays. ```APIDOC ## setOpenOtherPageWays() — External App Jump Strategy `OpenOtherPageWays` enum controls the behavior strategy when the WebView encounters a URL scheme that cannot be handled (e.g., invoking an external App). AgentWeb has built-in automatic handling for WeChat Pay (`weixin://`) and Alipay (`alipays://`). ```java // DERECT: Directly jump to the corresponding App, no prompt. // ASK: Prompt the user to confirm the jump (default behavior). // DISALLOW: Completely prohibit jumping to external Apps. mAgentWeb = AgentWeb.with(this) .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1)) .useDefaultIndicator() .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK) // Prompt for confirmation .isInterceptUnkownUrl(true) // Intercept unhandled URLs (default true) .createAgentWeb().ready() .go("https://payment.example.com/checkout"); // WeChat Pay: AgentWeb automatically intercepts weixin://wap/pay? and invokes WeChat, no extra configuration needed. // Alipay Pay: Requires additional dependency on the Alipay SDK in build.gradle // implementation files('libs/alipaySdk-xxx.jar') ``` ``` -------------------------------- ### setAgentWebWebSettings() — 自定义 WebSettings Source: https://context7.com/justson/agentweb/llms.txt Customize WebView settings by extending `AbsAgentWebSettings` or directly modifying the `WebSettings` object obtained via `getAgentWebSettings()`. ```APIDOC ## Customizing WebSettings ### Description Customize all WebView settings by extending `AbsAgentWebSettings` (internally implemented by `AgentWebSettingsImpl`) and overriding the `toSetting()` method. Alternatively, you can directly obtain the `WebSettings` object using `getAgentWebSettings()` for modifications. ### Methods **1. Directly Get and Modify `WebSettings`:** ```java mAgentWeb.getAgentWebSettings().getWebSettings().setUserAgentString("MyApp/1.0 AgentWeb"); ``` **2. Custom Settings Class (Recommended, Inject in Builder):** ```java public class SecureWebSettings extends AbsAgentWebSettings { @Override public IAgentWebSettings toSetting(WebView webView) { super.toSetting(webView); // Apply AgentWeb default configurations WebSettings settings = getWebSettings(); // Enhanced security configurations settings.setAllowFileAccess(false); settings.setAllowFileAccessFromFileURLs(false); settings.setAllowUniversalAccessFromFileURLs(false); // Custom User Agent settings.setUserAgentString( settings.getUserAgentString() + " MyApp/2.0" ); // Force offline cache (e.g., when offline) settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); return this; } } // Inject in the Builder: // mAgentWeb = AgentWeb.with(this) // .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1)) // .useDefaultIndicator() // .setAgentWebWebSettings(new SecureWebSettings()) // .createAgentWeb().ready().go(url); ``` ``` -------------------------------- ### AgentWeb WebView Lifecycle Management Source: https://context7.com/justson/agentweb/llms.txt Manage the WebView's lifecycle by calling methods from getWebLifeCycle() in your Activity/Fragment's corresponding lifecycle callbacks. This ensures proper resource release and prevents memory leaks. ```java @Override protected void onResume() { mAgentWeb.getWebLifeCycle().onResume(); super.onResume(); } @Override protected void onPause() { mAgentWeb.getWebLifeCycle().onPause(); // Pause all WebViews in the application super.onPause(); } @Override protected void onDestroy() { mAgentWeb.getWebLifeCycle().onDestroy(); // Destroy WebView and release resources super.onDestroy(); } ``` -------------------------------- ### Clear Cache Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Clear the disk cache for AgentWeb using `AgentWebConfig.clearDiskCache`. ```java AgentWebConfig.clearDiskCache(this.getContext()); ``` -------------------------------- ### Enable Location Services Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Declare the necessary permissions in AndroidManifest.xml to enable location services for AgentWeb. ```xml ``` -------------------------------- ### Apache License 2.0 Source: https://github.com/justson/agentweb/blob/androidx/README.md This code snippet displays the Apache License, Version 2.0, which governs the use of the AgentWeb library. Ensure compliance with the terms outlined in the license. ```text Copyright (C) Justson(https://github.com/Justson/AgentWeb) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` -------------------------------- ### Keep AgentWeb Classes for ProGuard Source: https://github.com/justson/agentweb/wiki/AgentWeb-基础使用 Configure ProGuard to prevent obfuscation of AgentWeb classes. This is crucial for the library to function correctly. ```java -keep class com.just.agentweb.** { *; } -dontwarn com.just.agentweb.** ``` -------------------------------- ### Custom WebViewClient Middleware for URL Interception Source: https://context7.com/justson/agentweb/llms.txt Implement a custom middleware to intercept specific URL schemes like 'myapp://' and handle them before the WebView loads them. This allows for custom deep link handling. ```java public class UrlInterceptMiddleware extends MiddlewareWebClientBase { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { String url = request.getUrl().toString(); if (url.startsWith("myapp://")) { // 处理自定义 scheme,阻止 WebView 继续加载 handleDeepLink(url); return true; } // 传递给下一个中间件或默认实现 return super.shouldOverrideUrlLoading(view, request); } private void handleDeepLink(String url) { Log.d("Middleware", "Deep link intercepted: " + url); } } ```