我正在尝试使用
Android API 10(sdk 2.3.3)开发具有WebView的自定义浏览器,不幸的是我不知道如何拦截网页中的请求,以便在新的浏览器窗口中打开URL,例如与target = “_空白”.
根据API文档,我已经覆盖了WebChromeClient的onCreateWindow,但是在点击这样的链接时不会调用它.可能是这个API级别的错误?我还会覆盖shouldOverrideUrlLoading,以避免WebView打开内置浏览器中的后续链接.
以下是我打开google.com的示例代码.要测试它,点击“新闻”,然后点击任何新闻标题. Android内置浏览器通常会在新的浏览器窗口中打开.
package com.myexample; import android.app.Activity; import android.os.Bundle; import android.os.Message; import android.util.Log; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; public class HelloAndroidActivity extends Activity { private static String TAG = "WebViewTest"; private WebView mWebView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG,"onCreate"); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.mywebview); mWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view,String url) { view.loadUrl(url); return true; } }); mWebView.setWebChromeClient(new WebChromeClient() { @Override public boolean onCreateWindow(WebView view,boolean dialog,boolean userGesture,Message resultMsg) { Toast.makeText(getApplicationContext(),"OnCreateWindow",Toast.LENGTH_LONG).show(); return true; } }); mWebView.loadUrl("http://www.google.com"); } }
解决方法
确保将supportMultipeWindows设置为true.没有它,WebChromeClient的onCreateWindow将永远不会被调用.
WebSettings settings = webView.getSettings(); settings.setSupportMultipleWindows(true);
然后注册一个WebChromeClient并覆盖onCreateWindow
webView.setWebChromeClient(new WebChromeClient() { @Override public boolean onCreateWindow(WebView view,Message resultMsg) { WebView newWebView = new WebView(getContext()); addView(newWebView); WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj; transport.setWebView(newWebView); resultMsg.sendToTarget(); return true; } });