Я пытаюсь реализовать функцию Web Share Api в своем веб-приложении, но когда я тестирую ее на своем iPhone 14 в Chrome, IOS

Программируем под IOS
Ответить Пред. темаСлед. тема
Anonymous
 Я пытаюсь реализовать функцию Web Share Api в своем веб-приложении, но когда я тестирую ее на своем iPhone 14 в Chrome,

Сообщение 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);
}
}
};


Подробнее здесь: https://stackoverflow.com/questions/793 ... but-when-i
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «IOS»