Невозможно загрузить 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), я получаю следующее сообщение об ошибке, как показано на рисунке.
Как я могу это решить?

Эй, ты нашел решение?
@RezaRahmati Еще нет
ты нашел решение?



Ответы 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 не удается открыть страницу или ошибка «Не удалось завершить операцию. Protocol error»
- Web-страница временно недоступна
- Нет подключения к интернет соединению
- Неверный адрес Web-страницы
- Устаревшая версия приложения, обновите или установите новый браузер из App Store
- Браузер Safari настроен неверно
- Разработчик Web-сайта запретил допуск или не добавил разрешение к допуску для открывания в этой программе.
Если у вас телефон перестал реагировать на зарядку или заряжается не полностью, читайте статью…
Способы решения появления ошибки
Первое, что необходимо сделать, это подождать некоторое время, т.к. возможно сайт, который вы хотите открыть, ограничен в работе из-за проведения технических работ, а администрация сайта на какое-то время прекратила доступ к ресурсу. Остается проверить доступ к иным страницам иных сайтов, ежели страницы открываются везде, кроме того, куда изначально пытались попасть, значит, сайт неактивен и траблы именно в нем.
Не знаете что делать если в вашем Айфоне закончилось свободная память? Статья в помощь…
Действенные методы решения
- Остановка JavaScript. В некоторых версиях операционной системы IOS есть ошибка, благодаря чему обозреватель Safari ограничивает допуск к некоторым сайтам. Чтобы решить такую проблему достаточно просто остановить джава скрипт. Открываем меню Настройки => Safari => Дополнения и переводим бегунок JavaScript в пассивное положение. После того, как вы получите возможность входа на необходимый сайт, следует проделать те же действия по включению ДжаваСкрипта обратно.
- Обнуление настроек Safari. Страницы web-сайта могут не отображаться из-за ошибки внутри приложения Сафари. Поэтому открываем меню Настройки => Safari => Очистить историю и данные сайтов.
- Отключение блокировки рекламы. В некоторых случаях юзеры 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.
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.
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.
My Angular application has a pdf download option. When i run my application in Iphone(IOS 12) Safari browser I get the following error message as shown in the image
How can i resolve it?

![]()
shizhen
11.9k9 gold badges52 silver badges86 bronze badges
asked Jan 24, 2019 at 4:57
![]()
3
If you are injecting an ancor tag into DOM programmatically as your solution, make sure you do not clear that up too soon.
For me 100ms worked fine but since it’s invisible either way I chose 1 second delay on clearing DOM up.
Example code:
this.fileApi.download(<your args>).subscribe((data: Blob) => {
const url = window.URL.createObjectURL(data);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = <your filename>;
document.body.appendChild(a);
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 1000);
})
answered Feb 3, 2020 at 12:19
3
My Angular application has a pdf download option. When i run my application in Iphone(IOS 12) Safari browser I get the following error message as shown in the image
How can i resolve it?

![]()
shizhen
11.9k9 gold badges52 silver badges86 bronze badges
asked Jan 24, 2019 at 4:57
![]()
3
If you are injecting an ancor tag into DOM programmatically as your solution, make sure you do not clear that up too soon.
For me 100ms worked fine but since it’s invisible either way I chose 1 second delay on clearing DOM up.
Example code:
this.fileApi.download(<your args>).subscribe((data: Blob) => {
const url = window.URL.createObjectURL(data);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = <your filename>;
document.body.appendChild(a);
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 1000);
})
answered Feb 3, 2020 at 12:19
3
The problem occur when using file download on IOS and using reload on the window displaying the blob.
Configuration:
Nothing special. PDFjs viewer.
Web browser and its version:
Operating system and its version: IOS 10.2
PDF.js version: 1.6.210.
Is an extension:
Steps to reproduce the problem: 1. 2.
- Using PDFViewer, after displaying a PDF, use the download file button.
- A new tab open that show the pdf in native pdf renderer of Safari.
- Use «reload» of the page : the page display an error instead of displaying the pdf again (in native pdf renderer of Safari)
What is the expected behavior? (add screenshot)
Best case : Display the pdf again (at least if the tab containing pdf.js displaying the pdf is still open)
Acceptable : empty page or user friendly message.
What went wrong? (add screenshot)
I get an error page like (approximatively translated from french) :
Safari cannot open this page.
Error: The operation cannot complete (WebkitBlobRessource error 1).
I get an error like (approximatively translated from french) :
Safari cannot open this page.
Error: The operation cannot complete (WebkitBlobRessource error 1).
Just reporting for documentation as I dont think there is a solution to this problem. The ressource have very likely been released from memory, maybe Webkit / Safari could display a more user friendly message ( I did a quick search on webkit but base but found no related issue).
У меня есть функция загрузки PDF в моем веб-приложении. Он отлично работает со всеми браузерами и iOS11, но он не работает в браузере Safari и ios12 на мобильных устройствах или iod pro. Я получаю ниже ошибки — Ошибка WebKitBlobResource 1
export const downloadPDF = (downloadLink, fileName, trackId, productId, historyId) => {
return (dispatch) => {
return request.doGetAuth(downloadLink).then(response => {
let contentType = response.headers.get('content-type');
if (_.includes(contentType, 'application/json')) {
return response.json();
} else {
return response.blob();
}
}).then(blobby => {
if (!blobby.message) {
const blob = new Blob([blobby], {
type: 'application/pdf'
});
if (isIos()) {
if (!isCriOs()) {
// For ios
let url = window.URL.createObjectURL(blob);
dispatch(downloadReadyAction(url, fileName));
} else {
// if chrome
let reader = new FileReader();
reader.onload = function(e) {
dispatch(downloadReadyAction(reader.result, fileName));
}
reader.readAsDataURL(blob);
}
} else {
FileSaver.saveAs(blob, fileName);
}
}
}).catch(err => {
console.log('Problem downloading pdf from server ' + err)
})
}
}