티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Android webview & localStorage

Android WebView & 로컬 스토리지

 문제 내용 

I have a problem with a webview which may access to the localStorage by an HTML5 app. The test.html file informs me that local storage is'nt supported by my browser (ie. the webview). If you have any suggestion..

HTML5 앱으로 로컬 스토리지에 액세스할 수 있는 웹 보기에 문제가 있습니다. test.html 파일은 나에게 로컬스토리지가 브라우저(webView)에서 지원되지 않는 것을 알려줍니다. 제안해주실게 있나요??

 

package com.test.HelloWebView; 
import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.KeyEvent; 
import android.webkit.WebChromeClient; 
import android.webkit.WebSettings; 
import android.webkit.WebStorage; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 

public class HelloWebView extends Activity { 

    WebView webview;

    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        webview = (WebView) findViewById(R.id.webview); 
        webview.getSettings().setJavaScriptEnabled(true); 
        webview.setWebViewClient(new HelloWebViewClient()); 
        webview.loadUrl("file:///android_asset/test.html"); 
        WebSettings settings = webview.getSettings(); 
        settings.setJavaScriptEnabled(true); 
        settings.setDatabaseEnabled(true); 
        String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); 
        settings.setDatabasePath(databasePath);
        webview.setWebChromeClient(new WebChromeClient() { 
        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { 
                quotaUpdater.updateQuota(5 * 1024 * 1024); 
            } 
        }); 
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) { 
            webview.goBack(); 
            return true; 
        } 
        return super.onKeyDown(keyCode, event); 
    }

    private class HelloWebViewClient extends WebViewClient { 
        public boolean shouldOverrideUrlLoading(WebView view, String url) { 
            view.loadUrl(url); 
            return true; 
        } 
    }
}

 

 

 높은 점수를 받은 Solution 

The following was missing:

다음 항목이 누락되었습니다.

 

settings.setDomStorageEnabled(true);

 

 

 가장 최근 달린 Solution 

This post came up a lot recently when I was looking for a similar solution. The webview WebSettings object has deprecated database path methods since API 19 which now return blank values, meaning we can't rely on them to pull the web page storage regardless of whether we enabled it on the settings prior to loading an URL.

최근 비슷한 해결책을 찾던 중 이 게시물이 많이 올라왔습니다. Webview WebSettings 개체는 API 19 이후 데이터베이스 경로 메서드를 더 이상 사용하지 않습니다. 이제 빈 값을 반환합니다. 즉, URL을 로드하기 전에 설정에서 활성화했는지 여부에 관계없이 데이터베이스 경로 메서드를 사용하여 웹 페이지 저장소를 가져올 수 없습니다.

 

In order to read localStorage values from a web page, we needed to extend the WebViewClient() and override onPageFinished(), in which you can evaluate javascript on the webview as demonstrated below:

웹 페이지에서 localStorage 값을 읽으려면 WebViewClient()를 확장하고 onPageFinished()을(를) 재정의해야 했습니다. 여기서 아래 설명된 대로 웹 뷰에서 javascript를 평가할 수 있습니다.

 

const val JAVASCRIPT_LOCAL_STORAGE_LOOKUP = "javascript:window.localStorage.getItem('KEY');"

...

override fun onPageFinished(view: WebView?, url: String?) {
    super.onPageFinished(view, url)
    view?.let { webView ->
        webView.evaluateJavascript(JAVASCRIPT_LOCAL_STORAGE_LOOKUP) { result ->
            // returns value from 'KEY'
        }
    }
}

Simply replace 'KEY' with the key of the stored object you want to access. This removes the need to provide any database implementation that may conflict with what you already have. Note that this will only poll the localStorage from the domain that the webview just finished loading. I hope this helps anyone else as it took me a bit of time to figure out.

'KEY'를 액세스할 저장된 개체의 키로 바꾸기만 하면 됩니다. 이렇게 하면 기존 데이터베이스와 충돌할 수 있는 데이터베이스 구현을 제공할 필요가 없습니다. 이 작업은 웹 보기가 방금 로드를 마친 도메인에서만 로컬 저장소를 폴링합니다. 나는 이것이 내가 알아내는 데 시간이 좀 걸렸기 때문에 다른 사람들에게 도움이 되기를 바란다.

 

 

 

출처 : https://stackoverflow.com/questions/5899087/android-webview-localstorage

반응형
댓글
공지사항
최근에 올라온 글