Skip to content
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

Support copying non-pngs and wait for focus to avoid race conditions #180322

Merged
merged 4 commits into from Apr 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 19 additions & 2 deletions extensions/media-preview/media/imagePreview.js
Expand Up @@ -354,10 +354,27 @@
copyImage();
});

async function copyImage() {
async function copyImage(retries = 5) {
if (!document.hasFocus() && retries > 0) {
// copyImage is called at the same time as webview.reveal, which means this function is running whilst the webview is gaining focus.
// Since navigator.clipboard.write requires the document to be focused, we need to wait for focus.
// We cannot use a listener, as there is a high chance the focus is gained during the setup of the listener resulting in us missing it.
setTimeout(() => { copyImage(retries - 1); }, 20);
return;
}

try {
await navigator.clipboard.write([new ClipboardItem({
'image/png': fetch(image.src).then(request => request.blob())
'image/png': new Promise((resolve, reject) => {
const canvas = document.createElement('canvas');
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
canvas.getContext('2d').drawImage(image, 0, 0);
canvas.toBlob((blob) => {
resolve(blob);
canvas.remove();
}, 'image/png');
})
})]);
} catch (e) {
console.error(e);
Expand Down