У кого-нибудь была такая же проблема? Я реализую API Web Share, и он работает, когда я тестировал его на своем рабочем столе, но когда я тестировал его на своем iPhone 14, он работает в Safari, но когда я использую Chrome, первые пару раз я нажимаю кнопку «Поделиться», и он работает. не работает, иногда это работает, а иногда нет, поэтому мне нужно рассылать спам, нажимая на него, надеясь, что в один из таких случаев это сработает, что также странно, так это то, что когда я использовал онлайн-виртуальную машину и тестировал ее на iphone12, она работала нормально, поэтому я не знаю, совместимость ли это проблема?
handleCopyOpen = async (socialHandle) => {
if (this.sharingInProgress) {
console.log('Sharing is already in progress.');
return;
}
this.sharingInProgress = true;
try {
const targetElement = document.querySelector('.milestone-popup');
if (!targetElement) throw new Error('Target element not found.');
// Get the Blob from the prepareScreenshot function
const blob = await this.prepareScreenshot(targetElement);
if (navigator.canShare && navigator.canShare({ files: [new File([blob], 'screenshot.png', { type: 'image/png' })] })) {
const file = new File([blob], 'screenshot.png', { type: 'image/png' });
await navigator.share({
title: 'Achievement on Fanstories',
text: 'Check out my latest achievement!',
files: [file],
});
console.log('Shared successfully using Web Share API');
} else {
console.warn('Web Share API not supported. Showing fallback.');
const url = URL.createObjectURL(blob);
window.open(url, '_blank');
}
} catch (error) {
if (error.name === 'AbortError') {
console.log('User canceled the share operation.');
} else {
console.error('Error during sharing:', error);
alert('Failed to share. Please try again.');
}
} finally {
this.sharingInProgress = false;
}
};
prepareScreenshot = async (targetElement) => {
// Define cloneContainer outside the try block for broader scope
let cloneContainer;
try {
// Clone the target element to avoid modifying the original DOM
cloneContainer = document.createElement('div');
cloneContainer.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: -1; /* Keeps the clone invisible */
opacity: 0; /* Ensures it's not visible to users */
`;
document.body.appendChild(cloneContainer);
const clonedElement = targetElement.cloneNode(true);
cloneContainer.appendChild(clonedElement);
// Adjust cloned content for capturing
const footerElement = clonedElement.querySelector('.share-footer');
const closeButtonElement = clonedElement.querySelector('.close-button');
const confettiCanvas = clonedElement.querySelector('canvas');
if (footerElement) footerElement.style.display = 'none';
if (closeButtonElement) closeButtonElement.style.display = 'none';
if (confettiCanvas) confettiCanvas.style.display = 'none';
// Allow DOM changes to reflect
await new Promise((resolve) => setTimeout(resolve, 100));
// Capture the screenshot
const canvas = await html2canvas(clonedElement, {
backgroundColor: null,
useCORS: true,
scale: 2, // High resolution
});
// Convert canvas to Blob
return new Promise((resolve, reject) => {
canvas.toBlob(
(blob) => {
if (blob) {
resolve(blob); // Return the Blob directly
} else {
reject(new Error('Failed to convert canvas to Blob.'));
}
},
'image/png', // MIME type
1.0 // Image quality (1.0 = best)
);
});
} catch (error) {
console.error('Error during screenshot preparation:', error);
throw error;
} finally {
// Ensure cloneContainer is cleaned up
if (cloneContainer) {
document.body.removeChild(cloneContainer);
}
}
};
Подробнее здесь: https://stackoverflow.com/questions/793 ... but-when-i
Я пытаюсь реализовать функцию Web Share Api в своем веб-приложении, но когда я тестирую ее на своем iPhone 14 в Chrome, ⇐ IOS
Программируем под IOS
1734962782
Anonymous
У кого-нибудь была такая же проблема? Я реализую API Web Share, и он работает, когда я тестировал его на своем рабочем столе, но когда я тестировал его на своем iPhone 14, он работает в Safari, но когда я использую Chrome, первые пару раз я нажимаю кнопку «Поделиться», и он работает. не работает, иногда это работает, а иногда нет, поэтому мне нужно рассылать спам, нажимая на него, надеясь, что в один из таких случаев это сработает, что также странно, так это то, что когда я использовал онлайн-виртуальную машину и тестировал ее на iphone12, она работала нормально, поэтому я не знаю, совместимость ли это проблема?
handleCopyOpen = async (socialHandle) => {
if (this.sharingInProgress) {
console.log('Sharing is already in progress.');
return;
}
this.sharingInProgress = true;
try {
const targetElement = document.querySelector('.milestone-popup');
if (!targetElement) throw new Error('Target element not found.');
// Get the Blob from the prepareScreenshot function
const blob = await this.prepareScreenshot(targetElement);
if (navigator.canShare && navigator.canShare({ files: [new File([blob], 'screenshot.png', { type: 'image/png' })] })) {
const file = new File([blob], 'screenshot.png', { type: 'image/png' });
await navigator.share({
title: 'Achievement on Fanstories',
text: 'Check out my latest achievement!',
files: [file],
});
console.log('Shared successfully using Web Share API');
} else {
console.warn('Web Share API not supported. Showing fallback.');
const url = URL.createObjectURL(blob);
window.open(url, '_blank');
}
} catch (error) {
if (error.name === 'AbortError') {
console.log('User canceled the share operation.');
} else {
console.error('Error during sharing:', error);
alert('Failed to share. Please try again.');
}
} finally {
this.sharingInProgress = false;
}
};
prepareScreenshot = async (targetElement) => {
// Define cloneContainer outside the try block for broader scope
let cloneContainer;
try {
// Clone the target element to avoid modifying the original DOM
cloneContainer = document.createElement('div');
cloneContainer.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: -1; /* Keeps the clone invisible */
opacity: 0; /* Ensures it's not visible to users */
`;
document.body.appendChild(cloneContainer);
const clonedElement = targetElement.cloneNode(true);
cloneContainer.appendChild(clonedElement);
// Adjust cloned content for capturing
const footerElement = clonedElement.querySelector('.share-footer');
const closeButtonElement = clonedElement.querySelector('.close-button');
const confettiCanvas = clonedElement.querySelector('canvas');
if (footerElement) footerElement.style.display = 'none';
if (closeButtonElement) closeButtonElement.style.display = 'none';
if (confettiCanvas) confettiCanvas.style.display = 'none';
// Allow DOM changes to reflect
await new Promise((resolve) => setTimeout(resolve, 100));
// Capture the screenshot
const canvas = await html2canvas(clonedElement, {
backgroundColor: null,
useCORS: true,
scale: 2, // High resolution
});
// Convert canvas to Blob
return new Promise((resolve, reject) => {
canvas.toBlob(
(blob) => {
if (blob) {
resolve(blob); // Return the Blob directly
} else {
reject(new Error('Failed to convert canvas to Blob.'));
}
},
'image/png', // MIME type
1.0 // Image quality (1.0 = best)
);
});
} catch (error) {
console.error('Error during screenshot preparation:', error);
throw error;
} finally {
// Ensure cloneContainer is cleaned up
if (cloneContainer) {
document.body.removeChild(cloneContainer);
}
}
};
Подробнее здесь: [url]https://stackoverflow.com/questions/79301311/im-trying-to-implement-the-web-share-api-functionality-on-my-web-app-but-when-i[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия