Webkitblobresource ошибка 1 что это

Невозможно загрузить PDF в браузере Safari на iphone или ipad pro ios12

В моем веб-приложении есть функция загрузки PDF-файлов. Он отлично работает со всеми браузерами и iOS11, но не работает в браузере Safari и ios12 на мобильных устройствах или iod pro. Я получаю ошибку ниже — Ошибка WebKitBlobResource 1

1 ответ

Когда мы открываем pdf на новой вкладке url, файл не существует, а его единственный кеш хранится внутри браузера. Поэтому, когда мы генерируем большой двоичный объект и перенаправляем на текущую вкладку, чтобы указать на сгенерированный URL-адрес большого двоичного объекта, мы теряем кеш. Так что открытие URL-адреса в новом окне помогает.

В моем приложении Angular есть возможность загрузки в формате PDF. Когда я запускаю свое приложение в браузере Safari Iphone (IOS 12), я получаю следующее сообщение об ошибке, как показано на рисунке.

Как я могу это решить?

ios_safari_issue

Эй, ты нашел решение?

@RezaRahmati Еще нет

ты нашел решение?

Формы c голосовым вводом в React с помощью Speechly

Flatpickr: простой модуль календаря для вашего приложения на React

Что такое cURL в PHP? Встроенные функции и пример GET запроса

Ответы 1

Если вы внедряете тег ancor в DOM программно в качестве своего решения, убедитесь, что вы не проясняете это слишком рано.

Для меня 100 мс работали нормально, но, поскольку они невидимы в любом случае, я выбрал 1-секундную задержку при очистке DOM.

как насчет открытия этого файла для загрузки / новой вкладки? а.цель = «_blank»; кажется, сломал его и a.download = title; не работает на иос

Здесь это не так, поскольку фактическая загрузка происходит через запрос API и как объект Blob. Например, если пользователь должен быть авторизован с помощью токена доступа.

IPhone Safari «Не удается открыть страницу» или ошибка «Не удалось завершить операцию. Protocol error»

Safari – мобильный интернет браузер, программа, приложение для просмотри web-страниц, чаще всего используется как стандартное приложение в устройствах Apple. И ошибку, которую мы сегодня рассматриваем, часто замечают пользователи IPhone и IPad. Поэтому предлагаю рассмотреть причины появления такой ошибки в вэб-браузере Сафари, а также способы ее устранения.

Ошибка в браузере Safari IPhone Не удается открыть страницу или не удалось завершить операцию. Protocol error

Ошибка в браузере Safari IPhone Не удается открыть страницу или не удалось завершить операцию. Protocol error

Причины, почему Safari не удается открыть страницу или ошибка «Не удалось завершить операцию. Protocol error»

  1. Web-страница временно недоступна
  2. Нет подключения к интернет соединению
  3. Неверный адрес Web-страницы
  4. Устаревшая версия приложения, обновите или установите новый браузер из App Store
  5. Браузер Safari настроен неверно
  6. Разработчик Web-сайта запретил допуск или не добавил разрешение к допуску для открывания в этой программе.

Если у вас телефон перестал реагировать на зарядку или заряжается не полностью, читайте статью…

Способы решения появления ошибки

Первое, что необходимо сделать, это подождать некоторое время, т.к. возможно сайт, который вы хотите открыть, ограничен в работе из-за проведения технических работ, а администрация сайта на какое-то время прекратила доступ к ресурсу. Остается проверить доступ к иным страницам иных сайтов, ежели страницы открываются везде, кроме того, куда изначально пытались попасть, значит, сайт неактивен и траблы именно в нем.

Не знаете что делать если в вашем Айфоне закончилось свободная память? Статья в помощь…

Действенные методы решения

  1. Остановка JavaScript. В некоторых версиях операционной системы IOS есть ошибка, благодаря чему обозреватель Safari ограничивает допуск к некоторым сайтам. Чтобы решить такую проблему достаточно просто остановить джава скрипт. Открываем меню Настройки => Safari => Дополнения и переводим бегунок JavaScript в пассивное положение. После того, как вы получите возможность входа на необходимый сайт, следует проделать те же действия по включению ДжаваСкрипта обратно.
  2. Обнуление настроек Safari. Страницы web-сайта могут не отображаться из-за ошибки внутри приложения Сафари. Поэтому открываем меню Настройки => Safari => Очистить историю и данные сайтов.
  3. Отключение блокировки рекламы. В некоторых случаях юзеры IPhone юзают различные блокираторы рекламы. Бывает так, что именно из-за этих приложений не открываются необходимые сайты. Для того, чтобы отключить такой блокиратор, необходимо просто зажать кнопку обновление страницы в браузере Сафари и в открывшемся окне следует нажать пункт Перезагрузить без блокировки контента.

Заключение

Надеюсь, приведенные способы решения проблемы помогли вам справиться с ошибкой «Не удается открыть страницу» или ошибка «Не удалось завершить операцию. Protocol error» на мобильных устройствах IPhone и IPad. Пишите результаты в комментариях; если проблема не решается, будем бороться с ней вместе!

Update TLDR;

Blobs in indexeddb are unreliable in iOS Webkit. So instead save your blobs as array buffer and the type of the blob as a string in the indexeddb. You can get the ArrayBuffer and the type of a blob-like this:

await blob.arrayBuffer()
blob.type

When you want to retrieve the data from the indexeddb and display it just create a new blob from the ArrayBuffer and type:

const blob = new Blob([value.buffer], { type: value.type });
URL.createObjectURL(blob);

Investigation

I have a very similar issue on iOS WebKit / safari: I also store images and video blobs received from the server in the indexeddb. The blobs are then retrieved and converted to an URL with createObjectUrl(). This works perfectly on all browser engines except WebKit / safari. iOS WebKit / safari only works the first couple of times. I have not found a perfect solution but I can share my findings so far:

Generally, all comments to similar issues are saying «blobs on WebKit are unreliable».

There are some possible workarounds: https://stackoverflow.com/a/60075517/13517617 I still have to try this one though.

Also what we may can do is use the fileReader to create a base64 String and use this as src. instead of createObjectUrl(). This can be achieved like this:

const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result
};

This is not an ideal solution as we now have some callbacks.

There are some hints pointing to that the mime type of the blobs have to be specified correctly to make it work in iOS WebKit / safari all the time.

I will dig deeper and share my final answer here. Maybe some else is faster or has encountered this issue before.

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@paintedbicycle

Describe the bug

In Safari, there is now a new error, where there wasn’t in previous versions.

Failed to load resource: The operation couldn’t be completed. (WebKitBlobResource error 1.)

The PDF then never renders in Safari.
This doesn’t happen in Chrome.

To Reproduce
Make and render a PDF in browser, using Safari.

    <PDFViewer style={{ height: '100%' }}>
      <Document>
        <Page size="A4" style={PDFStyles.page}>
          <View style={PDFStyles.section}>
             [Content]
          </View>
        </Page>
      </Document>
    </PDFViewer>

Desktop (please complete the following information):

  • OS: [e.g. MacOS]
  • Browser [e.g safari]
  • React-pdf version [e.g. v1.4.1]

@paintedbicycle
paintedbicycle

changed the title
Failed to load resource: The operation couldn’t be completed. (WebKitBlobResource error 1.)

[Regression] Failed to load resource: The operation couldn’t be completed. (WebKitBlobResource error 1.)

Mar 19, 2019

@diegomura

Thanks for reporting this. I couldn’t replicate it in desktop.
My OS is updated: macOS Mojave 10.14.3 (18D109).
Did you see this in desktop or mobile?

@paintedbicycle

It was desktop, yeah, all up to date. Latest react, etc, etc.

I’ll try to find some time in the next couple days to look into it further.

Paul

@paintedbicycle
paintedbicycle

changed the title
[Regression] Failed to load resource: The operation couldn’t be completed. (WebKitBlobResource error 1.)

Failed to load resource: The operation couldn’t be completed. (WebKitBlobResource error 1.)

Apr 16, 2019

@paintedbicycle

This appears to be caused by the use of <PDFViewer>. When I try to playground, it doesn’t happen and when I comment out the viewer, I can render it a bunch of times in a row successfully.

It happens on both localhost and a custom domain.

So, in Safari, it will sometimes render the PDF but then if you close the PDF and try again, it will often block — with the viewer opening, but a blank white PDF. Then, often closing the browser window and trying to render again will be successful. Other times you need to do that a few times. It’s quite inconsistent.

I’d say the error rate is about 30-40 percent of the times trying to render the, so it’s pretty frequent.

@paintedbicycle

Please let me know if there is anything I can get you to help troubleshoot and move this issue along. It effectively means Safari users cannot generate PDFs.

@ivantodorovich

@tchakabam

This issue happening on Safari is likely due to jamming the main event loop with either too long ticks i.e execution stacks. Or too many timeouts scheduled in a short time i.e too frequently.

That is what I was able to conclude, while I was seeing this error with a completely different type of application than this PDF lib here.

It seems that some microtasks then just get dropped of the queue, which causes some of the async blob-data-extraction resolutions to just fail like this :) It seems to be somewhat cut off in the depths of the runtime, as at the JS layer I would see this error in the console, but there wasnt any place where I could actually catch this promise rejection anywhere that it would claim :) Sort of buggy behavior indeed, at least as the catch-handlers I set on those Blob#arrayBuffer methods never get called (in my case I dont convert the data to a file for download, but I get data as messages from an RTC channel, which uses blobs internally).

EDIT: Was almost omitting to clearly give the helpful info to fix/workaround (but pretty much gave it above): When you try to access the blob data in any way, you need to make sure you reduce the «pressure» on the main thread in any way. That means, defer/slice all tasks in any way possible that might «block» it. Or even use a worker. Unfortunately the issue here is that this error seems not catchable that well, so it is not possible to implement retry (wasnt in my case at least).

@diegomura

Thanks @tchakabam for the explanation. Although I’m a bit lost on this subject. Do you think there’s something on this lib side that can be done? Also, if possible try using the 2.0 that ships better memory usage, it might be solved as well. Thanks!

I’m trying to read a rather big file in chunks using FileReader (File selected from a field). Works fine on Android, Chrome, Firefox etc., but somehow on iOS Safari the FileReader stops reading the chunks exactly after 60 seconds. The error I am seeing is WebkitBlobResource error 1. Makes me wonder if this is some kind of permission error or somehow iOS Safari revokes the File blob.

Sample code:

let file = <input type="file">

let chunkSizeToUse = (1024 * 1024) // 1 MB chunks
let offset = (0 - chunkSizeToUse)

let readInterval = setInterval(() => {
    if(offset < file.size){
        offset += chunkSizeToUse

        let fileReader = new FileReader()

        fileReader.onload = () => {
            let arrayBuffer = fileReader.result

            //further chunk processing
        }

        fileReader.onerror = (err) => {
            console.log(err) // WebkitBlobResource error 1 exactly after 60 seconds of processing
        }

        fileReader.readAsArrayBuffer(file.slice(offset, (offset + chunkSizeToUse)))
    }
    else{
        clearInterval(readInterval)
    }
}, 100)

For easier and direct debugging on an iOS device using Safari I’m gonna link this JSFiddle:

https://jsfiddle.net/L17uymvp

Just select a file and wait for the counter do go to zero.

All of this makes it impossible for some users to upload large files. Our webapp processes each chunk individually (encryption), so we have to work with chunks.

Apple Footer

  • This site contains user submitted content, comments and opinions and is for informational purposes
    only. Apple may provide or recommend responses as a possible solution based on the information
    provided; every potential issue may involve several factors not detailed in the conversations
    captured in an electronic forum and Apple can therefore provide no guarantee as to the efficacy of
    any proposed solutions on the community forums. Apple disclaims any and all liability for the acts,
    omissions and conduct of any third parties in connection with or related to your use of the site.
    All postings and use of the content on this site are subject to the
    Apple Support Community Terms of Use.
    See how your data is managed…

Copyright ©
Apple Inc. All rights reserved.

Понравилась статья? Поделить с друзьями:
  • Webmoney ошибка 103
  • Webasto f04 код ошибки
  • Webmoney ошибка 0x80004005
  • Webasto at 2000 stc коды ошибок
  • Webmoney коды ошибок