Cel*_*lEX 1 javascript url image paste
好的,例如,当我们在 Firefox 中对图像(不是图像位置)执行“复制图像”时,数据将被复制到剪贴板。如果我们粘贴到可编辑的文件中<div>并输出该文件的 HTML <div>,我们可以看到它是图像的实际 URL,而不是 base64 URL 或某些对象 URL。例如,如果我们将其粘贴到“画图”中,我们就会得到实际的图像。URL 是否嵌入到剪贴板数据中的某个位置?如果是这样,我们如何在粘贴上检索它?
以下是调用粘贴事件的代码:
let cd = (event.clipboardData || event.originalEvent.clipboardData);
for (item of cd.items) {
if (item.type.indexOf("image") >= 0) {
..... get the URL value ....
break;
}
}
Run Code Online (Sandbox Code Playgroud)
text/html您可以使用getDataDataTransfer 对象的方法通过数据类型访问标记数据。
然后您只需要解析该标记并搜索<img>'s src。
target.onpaste = (e) => {
const dT = e.clipboardData || window.clipboardData;
const html = dT.getData('text/html') || "";
const parsed = new DOMParser().parseFromString(html, 'text/html');
const img = parsed.querySelector('img');
if( !img ) { console.warn('no image here'); return; }
const url = img.src;
console.log(url);
};Run Code Online (Sandbox Code Playgroud)
#target { border: 1px solid }Run Code Online (Sandbox Code Playgroud)
<p><img id="img" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png">copy this image by right-click + "Copy Image"</p>
<div contenteditable id="target">Then paste here</div>Run Code Online (Sandbox Code Playgroud)