Skip to content

Instantly share code, notes, and snippets.

@ephemient
Created May 27, 2022 04:56
Show Gist options
  • Save ephemient/099fb6f8f6172a6f969185d1d33d6fd5 to your computer and use it in GitHub Desktop.
Save ephemient/099fb6f8f6172a6f969185d1d33d6fd5 to your computer and use it in GitHub Desktop.
Web Share Polyfill
// ==UserScript==
// @name Web Share Polyfill
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Implements Web Share API using clipboard and downloads
// @author ephemient
// @include https://*/*
// @grant none
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
if (!navigator.canShare && !navigator.share) {
navigator.canShare = (data) => true;
navigator.share = (data) => {
const {title, url, text, files} = data;
const body = [title, url, text].filter((element) => element).join('\n');
let promise = body ? navigator.clipboard.writeText(body).catch((error) => {
console.log(error);
alert(body);
}) : new Promise(undefined);
if (files) for (const file of files) {
promise = promise.then(() => {
new Promise((resolve, reject) => {
setTimeout(() => {
try {
const url = URL.createObjectURL(file);
const a = document.createElement('a');
a.href = url;
a.download = file.name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
resolve();
} catch (error) {
reject(error);
}
}, 500);
})
});
}
return promise;
};
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment