Err access denied android studio

WebView ERR_ACCESS_DENIED for local files on Android SDK 30 #71822

Comments

ertong commented Dec 7, 2020

Steps to Reproduce

Consider the following code

Test page contents

Run it on android 30 emulator/device.
If you have in build.gradle

everything works as expected (you see WebView with test contents).

But it if you change to

WebView shows net::ERR_ACCESS_DENIED

We can try to allow changing this setting from flutter widget (which is looks like not good, because setAllowFileAccessFromFileURLs is deprecated).

And/or, maybe better, to implement the recommended mechanism of intercepting url loading (WebViewAssetLoader). In this case, it will be possible to implement file loading from custom scheme in the own code.

The text was updated successfully, but these errors were encountered:

darshankawar commented Dec 7, 2020

@ertong
Add below permission in manifest and try again to see if it works:

ertong commented Dec 7, 2020

@darshankawar
Thanks for suggestion.
In my setup, result is the same SDK 29 — works, SDK 30 — access denied.

darshankawar commented Dec 7, 2020

Replicable when sdk is set to 30. It shows:

With sdk set to 29, data shows up properly:

flutter doctor -v

darshankawar commented Dec 7, 2020

Probably has to do with giving access to load local files / html with sdk 30.
May be similar to #27086

uc-dve commented Jun 18, 2021

Hey, I have the same issue, I can’t access any files from documentDirectory inside webview in SDK 30.
Any solution?

Aulig commented Sep 10, 2021 •

Adding webView.getSettings().setAllowFileAccess(true); in FlutterWebView.java works, as suggested by @ertong. The method is also not deprecated I think, the method below it in the docs (setAllowFileAccessFromFileURLs) is.

I guess we should make this configurable via Flutter as the Android docs mention security reasons as reasons why the default was set to false.

Surprised that this issues has so few likes considering that SDK 30 is a requirement for PlayStore submission now.

fengwenhua commented Sep 13, 2021

It works for me!

Aulig commented Sep 13, 2021

Are all of those necessary for you? For me it works with just webSettings.setAllowFileAccess(true);

rvgmartins commented Oct 14, 2021 •

what version of the webview are you using?

It didn’t works for me.

Aulig commented Oct 15, 2021

I put webView.getSettings().setAllowFileAccess(true); below the line webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
in plugins\packages\webview_flutter\android\src\main\java\io\flutter\plugins\webviewflutter\FlutterWebView.java

Hope it helps you @rvgmartins 🙂

alexagat commented Oct 21, 2021 •

While the webView.getSettings().setAllowFileAccess(true); fix works for v1.x.x of the webview_flutter package, I can’t seem to get it working on v2.1.1 (latest). Since the structure of FlutterWebView.java changed, I attempted to add webView.getSettings().setAllowFileAccess(true); into the FlutterWebView constructor but no luck.

Читайте также:  Расширения хром андроид антизапрет

@Aulig based on your code snippet, I’m assuming you were modifying a previous version of the package? Has anybody been able to get this working on a modern version of the package and if so, what code was modified?

Aulig commented Oct 21, 2021

While the webView.getSettings().setAllowFileAccess(true); fix works for v1.x.x of the webview_flutter package, I can’t seem to get it working on v2.1.1 (latest). Since the structure of FlutterWebView.java changed, I attempted to add webView.getSettings().setAllowFileAccess(true); into the FlutterWebView constructor but no luck.

@Aulig based on your code snippet, I’m assuming you were modifying a previous version of the package? Has anybody been able to get this working on a modern version of the package and if so, what code was modified?

Hi @alexagat — you’re correct, I modified an old version. I didn’t notice that it changed in newer versions. I’d assume that you could just add it to the webviewbuilder in the createWebView function something like this:

But I haven’t tested that. Or is that what you already tried Alex?

alexagat commented Oct 21, 2021 •

But I haven’t tested that. Or is that what you already tried Alex?

@Aulig correct, I tried a number of variations including adding the .setAllowFileAccess(true) as a chained call to the webViewBuilder (as your snippet shows). If I downgrade back to 1.0.7 (the version I was at before trying to upgrade to 2.1.1 ) the fix works.

I’ll have to bump the version 1 by 1 to try and identify the specific bump of the webview_flutter package that broke this fix unless anybody else has ideas..

Aulig commented Oct 21, 2021

But I haven’t tested that. Or is that what you already tried Alex?

@Aulig correct, I tried a number of variations including adding the .setAllowFileAccess(true) as a chained call to the webViewBuilder (as your snippet shows). If I downgrade back to 1.0.7 (the version I was at before trying to upgrade to 2.1.1 ) the fix works.

I’ll have to bump the version 1 by 1 to try and identify the specific bump of the webview_flutter package that broke this fix unless anybody else has ideas..

I see, that’s unfortunate. I think I forked off version 2.0.2, which works for me. So you can start your search there if you’d like. Good luck!

Источник

Android – не удается получить доступ к html файлу на SDCard

Я пытаюсь открыть html файл, который у меня есть на моей SD-карте в Chrome или любом другом веб-браузере (не html Viewer).

Я попытался ввести путь к файлу, подобный этому

Я получаю эту ошибку:

Что может быть неправильно?

EDIT: Я должен упомянуть, что я не разрабатываю приложение для Android. Я просто хочу просмотреть html файл, который находится на моей SD-карте в Chrome-браузере Chrome

EDIT2: он не работает с ext. sdcard, а также из внутренней памяти

Это происходит просто потому, что у хром-приложения нет разрешения на чтение внешнего хранилища.
если вам нужно такое приложение, вот ссылка.
Ниже приведен список разрешений на использование Chrome.

Ваши учетные записи

  • находить учетные записи на устройстве
  • добавлять или удалять учетные записи
  • использовать учетные записи на устройстве
  • прочитать конфигурацию службы Google

Ваше местоположение

  • приблизительное местоположение (на основе сети)
  • точное местоположение (GPS и сетевые)

Сетевая связь

  • просмотр сетевых подключений
  • контроль ближнего поля
  • получать данные из Интернета
  • полный доступ к сети

Место хранения

  • изменять или удалять содержимое вашего USB-накопителя

Системные инструменты

  • проверить доступ к защищенному хранилищу
  • устанавливать ярлыки
Читайте также:  Как посмотреть где последний раз был андроид

Закладки и история

  • писать веб-закладки и историю
  • прочитайте свои веб-закладки и историю

камера

  • фотографировать и видео

Микрофон

Влияет на аккумулятор

  • не позволять устройству спать
  • контроль вибрации

Настройки звука

  • измените настройки звука

Настройки синхронизации

  • читать статистику синхронизации
  • включить и выключить синхронизацию
  • параметры синхронизации для чтения

У меня была такая же проблема, и единственный способ решить проблему чтения html файла в Chrome на устройстве, которое не внедрено, – это скопировать или переместить файл html во внутреннюю память устройства.

Альтернативой является root-устройство и изменение разрешений для доступа к SD-карте в Chrome.

Один из способов обойти это было (на устройстве с загруженным хромом)

Источник

ERR_ACCESS_DENIED в веб-просмотре в Android

Я создал веб-приложение для Android Studio. но не загрузил веб-URL. ошибка net::ERR_ACCESS_DENIED. Может кто-нибудь помочь с этим

8 ответов

Для меня проблема была немного глупой, я изначально забыл добавить android:usesCleartextTraffic=»true» в манифесте и запустил приложение. После того, как я добавил android:usesCleartextTraffic=»true» это все еще дало ERR_ACCESS_DENIED . Затем я очистил данные, удалил приложение, переустановил его и бац, ошибка исчезла.

Я только начал разрабатывать приложения для Android и получил ту же ошибку, даже когда у меня было разрешение:

Затем я удалил приложение внутри эмулятора и построил его заново, и теперь приложение имеет доступ в Интернет.

Попробуйте добавить их в свой код веб-просмотра:

Если по-прежнему не работает, попробуйте добавить android:usesCleartextTraffic=»true» в тег приложения в манифесте.

Проверьте, предоставили ли вы Интернет-разрешение:

и поместите это в Манифест:

В моем случае это произошло после обновления моего приложения до SDK 30. И решение было:

Раньше значение по умолчанию было истинным, но в SDK 30 оно неверно. Таким образом, вам нужно явно разрешить доступ.

Помните, что если вам нужен интернет, вам нужно установить разрешение в манифесте, в верхней части добавить разрешение на использование тегов, например так

удаление, а затем переустановка сработали для меня.

Если не базовые разрешения, это также может произойти, если вы пытаетесь загрузить зашифрованную SSL-страницу (начиная с https://), и она выдает любую ошибку. Чтобы позаботиться об этом, вы можете добавить:

И для некоторых, пытающихся загрузить локальный файл, это также произошло из-за отсутствия у проекта разрешения на чтение, я не уверен, почему, но вы также можете попробовать добавить это в свой манифест:

Или вы можете использовать платформу Android Smart WebView, которая сама может устранить все подобные ошибки.

Источник

Android Question Webview- Access Denied with API 30

anglia

Member

I’m working on an app that creates a simple html file for users to view in a webview.
I’m trying to cater for all users including those with API 30 devices.

My html file is stored in the DirInternal folder which I thought was available to all users regardless of their Android version.

When I set the TargetSdkversion to 29 there is no problem and the web page displays correctly. However, setting the TargetSdkversion to 30 causes a problem.

I’m using a very simple html file named hello.html for a simple demonstration app.

No errors shown in the log but the message on the device is-

Web Page Not available
The web page at file:///data/data/b4aexample/files/hello.html could not be loaded because:
Net:ERR_ACCESS_DENIED

I’ve tried everything I can think of without success.

If anyone could tell me where I’m going wrong, I’d be very grateful.

FrostCodes

Active Member

Are you using XUI to load the page?

Here is an example of how I load mine.

drgottjr

Well-Known Member

the file:// url has been turned off as of api 30.
i think you can probably to turn it back on temporarily with webview extras 2.
the method is setfileallowaccess( true|false ).
enjoy it while it lasts. android doesn’t want you to use it, which means you
will soon not be allowed to use it.

Читайте также:  Серые обои для андроида

you can load your html this way, irrespective of api:

there is a new, dedicated api to handle file:// type urls:
androidx.webkit.WebViewAssetLoader. my guess is after the complaining
dies down, it will ultimately be the only way to load a webview from a file on
one’s device.

————————————————————————————————
UPDATE:
this is what assetloader looks like, and this is one example of how google wants you to do it:

i’ve tested it (both inline and as part of a library); it’s easy to set up and works as expected.
but it would be cleaner if someone maintaining an important library here
(eg, webviewextras or even the core) were to include it there, rather than adding a random
inline snippet which ends up conflicting with such a library. (the assetloader api requires a
webviewclient. if you have a custom webviewclient, you nullify the webviewclient created
in, eg, webviewextras.)

if you don’t need webviewextras then you’re free to create your own and implement the
assetloader api.

even if you don’t use webviewextras, our core webview provides functionality which is nullified
with a custom webviewclient. you would have to add those methods to your custom class if you
really wanted to use the webviewassetloader api and still use the standard webview.

for the purposes of a test, i only made a custom webviewclient. if google decides to do away
with file:// url’s to load a webview, assetloader will be required.

anglia

Member

Thanks to both of you for your suggestions.

The LoadHtml — file.readstring suggestion from drgottjr worked perfectly!
Do you think that this Loadhtml way of loading an HTML file will continue to be allowed by Google?

I only have a simple web page to display with no hyperlinks etc. and I’ll stick with this method for the time being.
I’ll need to study the Assetloader option a lot more before I try to use it.

drgottjr

Well-Known Member

the file:// url’s pose a potential security problem, per google. hence
the new scheme based on https:// (and the availability of a google-supplied
domain to be used in lieu of file://. you are not required to use that domain,
but if you’re loading locally kept files in a webview, that’s what you would use.)

loading anything is a potential security problem; there is no way to know when
google decides to deprecate and then disallow something as a security risk.
nothing is forever.

normally i would say it’s best to embrace whatever new scheme google devises,
since however you’re doing things now, you will probably be forced to change.
in this case, it’s a little tricky for the reason i mentioned previously.

you may be part of a very small minority using file:// url’s (or yugo vehicles), and no
one might ever find it appropriate to incorporate the assetloader api into b4a.
while you wait, the best option is probably the loadhtml(file.readstring()) solution. second
choice would be using webviewextras 2 and turn on setallowfileaccess (true). third
would be a custom fix (so long as you never need webviewextras or similar).

a highly influential point of view here is that webviews should not be used.
also, it’s your responsibility to keep abreast of changes in android. «it worked in 29 but
not in 30″ should be a big red flag for you.

Источник

Оцените статью