如果您的應用程式使用 WebView
顯示網頁內容,您可能會考慮改善點擊行為,原因如下:
WebView
不支援自訂網址配置項,如果點擊目的地是其他應用程式,系統可能會在廣告中傳回該配置項。舉例來說,Google Play 到達網址可能會使用market://
。
WebView
不支援 Google 登入和 Facebook 登入。
本指南提供最佳化步驟,協助您在保留網頁檢視畫面內容的同時,改善行動版網頁檢視畫面的點擊行為。
必要條件
- 完成「設定網頁檢視畫面」指南。
實作
請按照下列步驟,在 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, return early.
if (request.getUrl().getHost() == 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, return early.
request?.url?.host?.let { targetDomain ->
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
}
// 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
}
return false
}
}
}
}
測試網頁導覽
如要測試網頁導覽變更,請載入
https://webview-api-for-ads-test.glitch.me#click-behavior-tests
至網頁檢視畫面。點選各個不同連結類型,查看這些連結在應用程式中的運作方式。
建議您確認以下事項:
- 每個連結都會開啟指定的網址。
- 返回應用程式時,測試頁面的計數器不會重設為零,以驗證網頁狀態是否已保留。