Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

개발새발 블로그

WebView안에서 javascript 사용하기 본문

android

WebView안에서 javascript 사용하기

SeanBlog 2019. 12. 5. 18:30

webViewSetting()

 private void webViewSetting(){
 
        mView.webView.setWebViewClient( new CustomWebViewClient() );
        mView.webView.setWebChromeClient(new CustomWebCromeClient());
        mView.webView.setDownloadListener(downloadListener);
 
        WebSettings webSettings = mView.webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        //html5 local storage 사용설정
        webSettings.setDomStorageEnabled(true);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setTextZoom(100);
 
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
 
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setAppCacheEnabled(true);
 
        //zoom
        webSettings.setSupportZoom( true );
        webSettings.setBuiltInZoomControls( true );
        webSettings.setDisplayZoomControls( false );
 
//        webSettings.setUserAgentString(webSettings.getUserAgentString() + " "
//                + "SKBIZMALL-app-Agent: " + "SKOHCAR "
//                + "SKBIZMALL-app-Platform: A " + Util.getVersionName(this)
//                + "Sser-Agent: " + "SKOHCAR" );
//        mView.webView.loadUrl( WEBVIEW_LOAD_URL );
        ShowToast("테스트 URL ");
        mView.webView.loadUrl("http://1.235.32.173:4380/app/appTest.html");
   }

<WebViewClient>

 private class CustomWebViewClient extends WebViewClient {
 
 
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            DLog.d(TAG, "onReceivedError : " + error.getErrorCode() + ", " + error.getDescription());
            super.onReceivedError(view, request, error);
        }
 
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
        }
 
 
        @Override
        public void onPageFinished(WebView view, String url) {
            //페이지 끝날 때 호출
            super.onPageFinished(view, url);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                CookieSyncManager.getInstance().sync();
            } else {
                CookieManager.getInstance().flush();
            }
        }
        @Override
        public boolean shouldOverrideUrlLoading( WebView view, WebResourceRequest request )
        {
            return super.shouldOverrideUrlLoading( view, request );
        }
 
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
 
            if (url != null && url.startsWith("sean://test_download") ) {
                Toast.makeText(mCtx, "test_download", Toast.LENGTH_SHORT).show();
                mUrl = url;
 
                setPermission( writePermissionListener, Manifest.permission.WRITE_EXTERNAL_STORAGE );
                return true;
            }else if (url != null && url.startsWith("tel:") ) {
                Uri phoneNum = Uri.parse(url);
                startActivity(new Intent(Intent.ACTION_DIAL, phoneNum));
                return true;
 
            }else if (url != null && url.startsWith("skohcar://openFile") ) {
 
                mUrl = url;
 
                setPermission( writePermissionListener, Manifest.permission.WRITE_EXTERNAL_STORAGE );
                return true;
            } else if (url != null && url.startsWith("skohcar://outLink") ) {
 
                //Outlink
                try {
                    if( url.contains("url=")){
                        Uri tempUri = Uri.parse(url);
                        Uri outLinkUri = Uri.parse( tempUri.getQueryParameter("url") );
                        Intent intent = new Intent(Intent.ACTION_VIEW, outLinkUri);
                        startActivity(intent);
                    }
                } catch ( Exception e ){
                    DLog.e( TAG, e.toString() );
                }
 
 
                return true;
            } else if (url != null) {
                Toast.makeText(mCtx, url, Toast.LENGTH_SHORT).show();
                return true;
            }
 
            return super.shouldOverrideUrlLoading(view, url);
        }
 
    }
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

<DownLoad Litener>

 DownloadListener downloadListener = new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            try {
                MimeTypeMap mtm = MimeTypeMap.getSingleton();
                DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                Uri downloadUri = Uri.parse(url);
 
                final String fileName = URLDecoder.decode(downloadUri.getQueryParameter("ORIG_FILE_NM1"), "UTF-8");
 
                // MIME Type을 확장자를 통해 예측한다.
                String fileExtension = fileName.substring(fileName.lastIndexOf('.'+ 1, fileName.length()).toLowerCase();
                String mimeType2 = mtm.getMimeTypeFromExtension(fileExtension);
 
                // Download 디렉토리에 저장하도록 요청을 작성
                DownloadManager.Request request = new DownloadManager.Request(downloadUri);
                request.setTitle(fileName);
                request.setDescription(url);
                request.setMimeType(mimeType2);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
 
                final File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                path.mkdirs();
 
                IntentFilter completeFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
                downloadReceiver = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        Toast.makeText(MainActivity.this, fileName + getString( R.string.newline_download_complete ), Toast.LENGTH_SHORT).show();
                        unregisterReceiver(downloadReceiver);
                    }
                };
                registerReceiver(downloadReceiver, completeFilter);
 
                downloadManager.enqueue(request);
 
            } catch (Exception e) {
                DLog.e(TAG, e.toString() );
                setPermission(new PermissionListener() {
                    @Override
                    public void onPermissionGranted() { }
                    @Override
                    public void onPermissionDenied(List<String> arrayList) { }
                }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
        }
    };
r
 

<App단에서 javaScript호출하기>

    @RequiresApi( api = Build.VERSION_CODES.KITKAT )
    private void rtnWebPageGoBack(){
 
        try {
            mView.webView.evaluateJavascript("javascript:layerClose(5)", bValue -> {
                Toast.makeText(mCtx, String.valueOf(bValue), Toast.LENGTH_SHORT).show();
//                if( bValue.equalsIgnoreCase("false")){
//                    runBackPage();
//                }
            });
        } catch ( Exception e ){
            DLog.e( TAG, e.toString());
        }
    }
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
Comments