WebView頁面中標籤是target="_blank"時創建新窗口無響應

如果WebView頁面中鏈接的<a>標籤是target=”_blank”,而你的WebView又沒有做任何處理,這個時候就會點擊無效的狀況,是不是很莫名其妙?

target由多個定義類型
_blank:表示將鏈接打開新窗口
_self:表示在目前窗口或框架裏打開鏈接(默認的)
_parent:表示在父窗口或框架裏打開鏈接
_top:表示在頂層框架裏打開新鏈接
另外還可以直接把框架名稱指定給target,表示在某個框架也中打開鏈接,像csdn這樣點擊左面的目錄樹,在右邊打開新鏈接就是這種!

解決方案也簡單,繼承WebChromeClient,重寫onCreateWindow是關鍵,

一、首先設置,不然不會走回調:

webSetting.setSupportMultipleWindows(true);
二、然後請看代碼:
@Override
public boolean onCreateWindow(WebView webView, boolean isDialog, boolean isUserGesture, Message resultMsg) {

    X5WebView x5WebView = new X5WebView(activity);


    X5WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
    x5WebView.setWebChromeClient(new CustomWebChromeClient(activity));
    x5WebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //攔截url,跳轉新窗口
            if (activity != null) {
                Intent intent = new Intent(activity, MyWebActivity.class);
                intent.putExtra(Constants.INTENT_KEY_URL, url);
                activity.startActivity(intent);
            }
            //防止觸發現有界面的WebChromeClient的相關回調
            return true;
        }
    });
    transport.setWebView(x5WebView);
    resultMsg.sendToTarget();

    return true;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章