Translate

[Android] WebView의 Local File(html) 로딩 시 jQuery 로 jsonp 사용이 안되는 문제



다음의 소스에서..
            $.ajax({
                type: 'POST',
                url: 'http://www.google.co.kr',
                dataType: 'jsonp',
                success: function(res) {
                    console.log('success: ' + res);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log('error: \njqXhR: ' + jqXHR + '\ntextStatus: ' + textStatus + '\nerrorThrown: ' + errorThrown);
                },
                timeout: function(e) {
                    console.log('timeout: ' + e);
                },
                complete: function(e) {
                    console.log('complete: ' + e);
                }
            });



같은 소스를 WebServer 에 올려서 해당 URL을 로딩하면 정상적으로 작동하는 소스가
안드로이드의 assets 디렉토리에 넣고 WebView 에 file:///android_asset/index.html 이렇게 로드를 했을 경우에는 에러가 발생하는 문제가 있었다.



Logcat 을 찍었을 때 다음과 같이 표시가 되었다.
E/MyActivity( 2076): error:
E/MyActivity( 2076): jqXhR: [object Object]
E/MyActivity( 2076): textStatus: error
E/MyActivity( 2076): errorThrown: Method Not Allowed
E/MyActivity( 2076): LOG
E/MyActivity( 2076): file:///android_asset/index.html
E/MyActivity( 2076): complete: [object Object]
E/MyActivity( 2076): LOG
E/MyActivity( 2076): file:///android_asset/index.html



소스를 수정해보며 한참 삽질을 해보니.. 위에 적혀있는대로..

결론은 서버에서 지원되지 않는 메소드(POST)를 사용해서 그렇다.


Google은 서버에서 POST 메소드를 지원하지 않는다.(POST 요청시 응답코드 405)
jsonp 기술은 GET방식을 이용을 하는데 일반 브라우저에서는 type 을 POST라고 써도
GET방식으로 변환되어 전송되는 것으로 알고있다.
하지만 안드로이드의 Local File(html) 에서는 기술해 놓은 POST로 그대로 나가고 있었다.






그리고 jsonp 를 사용하는 이유가 크로스도메인 이슈를 해결하기 위해 사용을 하는건데
Android의 Webview에서 Local File(html)을 로드했을 시 jsonp 를 사용하지 않더라도 크로스도메인 이슈가 발생하지 않고 정상적으로 동작이 가능했었다.


즉 다음 소스가 크로스도메인 이슈 없이 작동을 한다는 거다.
        $.ajax({
            type: 'GET',
            url: 'http://www.google.co.kr',
            success: function(res) {
                console.log('success: ' + res);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log('error: \njqXhR: ' + jqXHR + '\ntextStatus: ' + textStatus + '\nerrorThrown: ' + errorThrown);
            },
            timeout: function(e) {
                console.log('timeout: ' + e);
            },
            complete: function(e) {
                console.log('complete: ' + e);
            }
        });



그리고 웹뷰의 설정에 다음이 포함되어야 Ajax 사용이 가능했었다.
        WebView webview = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);



테스트했던 소스를 업로드 했다.
소스 다운로드


댓글