티스토리 뷰

안드로이드 로컬 웹뷰(file:///android_asset/index.html)에서 내부 파일을 ajax로 불러올 때 cross origin 이슈가 발생합니다.


아래는 test.json 파일을 로드하는 예시입니다.

$.ajax({
    url : "test.json",
    success : function (data) {
        console.log(data);
    }
});

이 스크립트 실행 시 아래와 같은 에러가 발생합니다.

Access to XMLHttpRequest at 'file:///android_asset/test.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, https.

이 에러는 안드로이드 웹뷰 세팅으로 해결할 수 있습니다.

WebSettings webViewSetting = webView.getSettings();

webViewSetting.setAllowFileAccessFromFileURLs(true);
webViewSetting.setAllowUniversalAccessFromFileURLs(true);

그전에 인터넷 권한도 잊으면 안 됩니다.

<uses-permission android:name="android.permission.INTERNET"/>
댓글