如何在Javascript的copy事件中通过URL复制本地Blob文件?
问题与尝试代码
我设置了一个copy事件,代码如下:
// in reality this blob is arbitrary it could be even an executable // the url doesn't have to be blob but it could be blob const url: string = "blob://..."; document.addEventListener('copy', async function (e) { const xhr = new XMLHttpRequest(); xhr.open('GET', url, false); // Synchronous request because it will not work with async // xhr.responseType = 'arraybuffer'; // commented out because it will be rejected and crash the code xhr.overrideMimeType('text/plain; charset=x-user-defined'); xhr.send(null); if (xhr.status === 200) { // yes I know this isn't binary but there's nothing I can do since responseType arrayBuffer is not allowed hence both response and responseText are strings const binary = xhr.responseText; // this is corrupted anyway const dataUri = `data:${xhr.getResponseHeader('content-type')};base64,${btoa(binary)}`; // Set the data URI to the clipboard alongside the copied text const text = window.getSelection().toString(); e.clipboardData.setData('text/plain', text); e.clipboardData.setData('text/uri-list', dataUri); console.log(dataUri); e.preventDefault(); } });
无论怎么尝试都无法成功,核心问题是没办法通过请求生成有效的data URI,而且异步请求不被允许。
我还尝试了直接传入data URI的测试代码:
e.preventDefault(); const image = await fetch(url).then(response => response.blob()); const data = await blobToDataURL(image); const text = new Blob(['Cute sleeping kitten'], {type: 'text/plain'}); const html = new Blob([`<img src=${data}>`], {type: 'text/html'}); const item = new ClipboardItem({ 'text/plain': text, "text/html": html, }); await navigator.clipboard.write([item]);
这种方法同样无效,在paste事件中,e.clipboardData.getData("text/plain")或"text/html"都返回空值。
看起来目前不支持从Blob复制文件。需要说明的是,这些文件不存在于任何服务器,URL仅在当前场景有用,大多是存储在本地indexedDB中的Blob,基于服务器的解决方案不适用。
内容的提问来源于stack exchange,提问作者Onza
相关产品推荐
相关产品推荐

