3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Android 11以降でWebViewでローカルHTMLが表示できないとき

Posted at

※本記事は、NativeScript-Vueのコードを提示していますが、考え方は、どの開発言語・フレームワークでも同一と思われます。予めご了承ください。

陥った事象

最近、NativeScript-Vueというものを使って、Androidネイティブアプリケーションを試しに作ってみたりしています。Vue.jsに慣れている人であれば、楽にネイティブアプリを作ることができるということで、使わせてもらっています。

さて、開発をしている最中に、UIコンポーネントの1つである「WebView」を使って、アプリ内のアセットとして配置しているHTMLファイルを表示させたい場面がありました。

通常であれば、NativeScript-Vueの場合、次のように書きます。

./src/components/App.vue
<template>
  <Frame>
    <Page>
      <GridLayout columns="*" rows="*">
        <!-- ↓ここでWebViewコンポーネントを配置して、srcとしてassetsディレクトリ内のファイルを指定 -->
        <WebView row="0" col="0" src="~/assets/index.html" />
      </GridLayout>
    </Page>
  </Frame>
</template>

しかしこの状態で、アプリをAndroid 11上で動作させると、次のような「ERR_ACCESS_DENIED」という表示になってしまいました。エミュレータでも実機でも同様です。

ERROR

そして、試しにAndroid 10のエミュレータで動作確認すると、正常に表示されるのです。

解決方法

Androidのリファレンスに次のようなことが書かれていました。

setAllowFileAccess

The default value is true for apps targeting Build.VERSION_CODES.Q and below, and false when targeting Build.VERSION_CODES.R and above.

バージョンコードR(つまりAndroid 11)から、WebSettingsのAllowFileAccessの設定が、デフォルトでfalseになっていますよ、とのことです。ですので、明示的にtrueにしてあげることで、解決できそうです。

NativeScript-Vueの場合、次のように、Loadedイベントと組み合わせることで、解決できました。

./src/components/App.vue
<template>
  <Frame>
    <Page>
      <GridLayout columns="*" rows="*">
        <!-- ↓ここでWebViewコンポーネントを配置して、loadedイベントを捕捉 -->
        <WebView row="0" col="0" @loaded="webViewLoaded" />
      </GridLayout>
    </Page>
  </Frame>
</template>

<script lang="ts">
export default {
  methods: {
    // loadedイベントが発生した時の処理
    webViewLoaded(args) {
      if (args.object.android) {
        args.object.android.getSettings().setAllowFileAccess(true); // ここで、setAllowFileAccessメソッドを使って、trueにする
        args.object.src = "~/assets/map/index.html"; // 上記設定をしてから、ファイルを初めて読み込む
      }
    },
  },
};
</script>

ただ、同リファレンスにも少し書かれているのですが、このような方法でHTMLを表示させるよりも、より安全な方法があるのかもしれません。


※結局自己解決したのですが、もともとStackOverflowで質問していました

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?