如果應用程式使用
WebView
顯示網頁內容,建議您基於下列原因,考慮最佳化點擊行為:
WebView
不支援自訂網址架構,如果點擊目的地是其他應用程式,廣告中可能會傳回這類架構。舉例來說,Google Play 點擊後到達網址可能會使用market://
。
- Google 登入
和 Facebook 登入
不支援
WebView
。
本指南提供建議步驟,協助您在保留網頁檢視內容的同時,最佳化行動版網頁檢視中的點擊行為。
必要條件
- 完成「設定網頁檢視畫面」指南。
導入作業
請按照下列步驟,在WebView
執行個體中最佳化點擊行為:
覆寫
WebViewClient
上的shouldOverrideUrlLoading()
。 當系統即將在目前的WebView
中載入網址時,就會呼叫這個方法。決定是否要覆寫點擊網址的行為。
程式碼範例會檢查目前網域是否與目標網域不同。這只是一種方法,您使用的條件可能有所不同。
決定要在外部瀏覽器、Android 自訂分頁或現有網頁檢視畫面中開啟網址。本指南說明如何啟動 Android 自訂分頁,開啟導向網站外部的網址。
程式碼範例
首先,請將 androidx.browser
依附元件新增至模組層級的 build.gradle
檔案 (通常為 app/build.gradle
)。自訂分頁必須符合下列條件:
dependencies {
implementation 'androidx.browser:browser:1.5.0'
}
下列程式碼片段說明如何實作 shouldOverrideUrlLoading()
:
Java
public class MainActivity extends AppCompatActivity {
private WebView webView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ... Register the WebView.
webView = new WebView(this);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(
new WebViewClient() {
// 1. Implement the web view click handler.
@Override
public boolean shouldOverrideUrlLoading(
WebView view,
WebResourceRequest request) {
// 2. Determine whether to override the behavior of the URL.
// If the target URL has no host and no scheme, return early.
if (request.getUrl().getHost() == null && request.getUrl().getScheme() == null) {
return false;
}
// Handle custom URL schemes such as market:// by attempting to
// launch the corresponding application in a new intent.
if (!request.getUrl().getScheme().equals("http")
&& !request.getUrl().getScheme().equals("https")) {
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
// If the URL cannot be opened, return early.
try {
MainActivity.this.startActivity(intent);
} catch (ActivityNotFoundException exception) {
Log.d("TAG", "Failed to load URL with scheme:" + request.getUrl().getScheme());
}
return true;
}
String currentDomain;
// If the current URL's host cannot be found, return early.
try {
currentDomain = new URI(view.getUrl()).toURL().getHost();
} catch (URISyntaxException | MalformedURLException exception) {
// Malformed URL.
return false;
}
String targetDomain = request.getUrl().getHost();
// If the current domain equals the target domain, the
// assumption is the user is not navigating away from
// the site. Reload the URL within the existing web view.
if (currentDomain.equals(targetDomain)) {
return false;
}
// 3. User is navigating away from the site, open the URL in
// Custom Tabs to preserve the state of the web view.
CustomTabsIntent intent = new CustomTabsIntent.Builder().build();
intent.launchUrl(MainActivity.this, request.getUrl());
return true;
}
});
}
}
Kotlin
class MainActivity : AppCompatActivity() {
private lateinit var webView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ... Register the WebView.
webView.webViewClient = object : WebViewClient() {
// 1. Implement the web view click handler.
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
// 2. Determine whether to override the behavior of the URL.
// If the target URL has no host and no scheme, return early.
if (request?.url?.host == null && request.url.scheme == null) {
return false
}
val currentDomain = URI(view?.url).toURL().host
// Handle custom URL schemes such as market:// by attempting to
// launch the corresponding application in a new intent.
if (!request.url.scheme.equals("http") &&
!request.url.scheme.equals("https")) {
val intent = Intent(Intent.ACTION_VIEW, request.url)
// If the URL cannot be opened, return early.
try {
this@MainActivity.startActivity(intent)
} catch (exception: ActivityNotFoundException) {
Log.d("TAG", "Failed to load URL with scheme: ${request.url.scheme}")
}
return true
}
val targetDomain = request.url.host
// If the current domain equals the target domain, the
// assumption is the user is not navigating away from
// the site. Reload the URL within the existing web view.
if (currentDomain.equals(targetDomain)) {
return false
}
// 3. User is navigating away from the site, open the URL in
// Custom Tabs to preserve the state of the web view.
val customTabsIntent = CustomTabsIntent.Builder().build()
customTabsIntent.launchUrl(this@MainActivity, request.url)
return true
}
}
}
}
測試網頁導覽
如要測試網頁導覽變更,請載入
https://google.github.io/webview-ads/test/#click-behavior-tests
到網頁檢視畫面。點選各種類型的連結,即可查看連結在應用程式中的行為。
建議您確認以下事項:
- 每個連結都會開啟預期網址。
- 返回應用程式時,測試頁面的計數器不會重設為零,以驗證頁面狀態是否保留。