안드로이드

[안드로이드] WebView 에서 window.open 기능과 a태그의 target='_blank' 새창 기능 구현하기

http://portfolio.wonpaper.net 2021. 10. 29. 21:42

일단 필자의 다른 포스팅에서 [안드로이드] javascript 의 window.open , window.close 연동하기 라는 내용은 앞서 설명한다 있는데

 

[안드로이드] javascript 의 window.open , window.close 연동하기

 

[안드로이드] javascript 의 window.open , window.close 연동하기

우리가 웹브라우저에 이미 탑재된 기능이라 지나칠수 있는데, 새창 띄우기 기능인 javascript 의 window.open 함수도 안드로이상에서는 따로 만들어 주어야 한다. 아래의 소스중에 WebChromeClient 상속받

wonpaper.tistory.com

html의 a태그의 href="" 하고 target='_blank' 형태로 새창이 뜨는 경우 안드로이드 상으로는 window.open와 동일한 형태로 처리된다.

 

WebChromeClient 상속받은 MyWebChromeClient 클래스내에 onCreateWindow함수

 

요놈의 영역이다.

 

그리고, 팝업형태의 window.open 과 a태그의 target='_blank' 를 구분하는 인자로 onCreateWindow 의 매개변수인 boolean isDialog 으로 잡고 구분하여 처리하였다.   

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
public class MainActivity extends AppCompatActivity {
 
    private static final String TAG = "MainActivity";
    private WebView webView1;
    private WebSettings webSettings;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        webView1 = (WebView) findViewById(R.id.webView1);
 
        webSettings = webView1.getSettings();
        webSettings.setJavaScriptEnabled(true);         // 자바스크립트 허용
        webSettings.setSupportMultipleWindows(true);    // 새창 띄우기 허용
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); // 자바스크립트 새창 띄우기 허용
        webSettings.setLoadWithOverviewMode(true);      // 메타태그 허용
        webSettings.setUseWideViewPort(true);           // 화면 사이즈 맞추기 허용
        webSettings.setSupportZoom(true);              // 화면줌 허용 여부
        webSettings.setBuiltInZoomControls(false);      // 화면 확대 축소 허용 여부
 
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);        // 브라우저 노캐쉬
        webSettings.setDomStorageEnabled(true);         // 로컬저장소 허용
 
        webView1.setWebChromeClient(new MyWebChromeClient()); 
        webView1.setWebViewClient(new WebViewClientClass(getApplicationContext()));
        webView1.loadUrl("http://www.naver.com");
    }
 
    // WebView 에서 url 변경시 그대로 이동되도록
    public class WebViewClientClass extends WebViewClient {
        private String TAG = "WebViewClientClass";
        private Context mApplicationContext = null;
        public WebViewClientClass(Context _applicationContext) {
            mApplicationContext = _applicationContext;
        }
 
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Log.d("WebViewClient URL : ", request.getUrl().toString());
            view.loadUrl(request.getUrl().toString());
            return true;
            // return super.shouldOverrideUrlLoading(view, request);
        }
    }
 
 
    public class MyWebChromeClient extends WebChromeClient {
        private final String TAG = "MyWebChromeClient";
 
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            Log.i(TAG,"onProgressChanged(view:"+view.toString()+ ", newProgress:"+newProgress+")");
        }
 
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            Log.i(TAG, "window.open 협의가 필요합니다.");
            WebView newWebView = new WebView(view.getContext());
            WebSettings webSettings = newWebView.getSettings();
            WebSettings settings = newWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setSupportMultipleWindows(true);
 
 
            // 다이얼로그창 형태인가 ? true (window.open 팝업창), false (href _blank 새창)
            if (!isDialog) {
 
                // 사용자가 웹뷰에서 클릭한 정보 취득
                WebView.HitTestResult result = view.getHitTestResult();
                String data = result.getExtra();
 
                Context context = view.getContext();
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(data));
                context.startActivity(browserIntent);
 
 
 
            } else {
 
                //final Dialog dialog = new Dialog(view.getContext(),R.style.Theme_DialogFullScreen);
                final Dialog dialog = new Dialog(view.getContext());
                dialog.setContentView(newWebView);
                dialog.show();
                dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
 
                        if (keyCode == KeyEvent.KEYCODE_BACK) {
                            dialog.dismiss();
                            newWebView.loadUrl("javascript:self.close();");
                            return true;
                        } else {
                            return false;
                        }
                    }
                });
 
                newWebView.setWebViewClient(new WebViewClientClass(view.getContext()));
                newWebView.setWebChromeClient(new MyWebChromeClient() {
                    @Override
                    public void onCloseWindow(WebView window) {
                        dialog.dismiss();
                        window.destroy();
                    }
                });
            } // end of if
 
 
 
            newWebView.setDownloadListener(new DownloadListener() {
                public void onDownloadStart(String url, String userAgent,
                                            String contentDisposition, String mimetype,
                                            long contentLength) {
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);
                }});
 
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(newWebView);
            resultMsg.sendToTarget();
 
            return true;
        } 
 
        @Override
        public void onCloseWindow(WebView window) {
            Log.i(getClass().getName(), "onCloseWindow");
            window.setVisibility(View.GONE);
            window.destroy();
            super.onCloseWindow(window);
        }
  
    }
   
}
cs

참고 : https://wellsw.tistory.com/37