1: the new API h5 navigator. Clipboard. Write to write to the clipboard
2: This API is designed to have large permissions, so only HTTPS can be deployed to use, of course, the local environment can be adjusted
3: Copy textnavigator.clipboard.writeText('Linr Text to be copied')
4: Copy images auxiliary images currently only support PNG type, so other types of images need to be converted to PNG type, this article only realized JPG files to PNG
Idea 1) : Use FETCH to obtain bold stream (if the server does not support FETCH to obtain images, please configure ngniX
location ^~ / { root html; index index.html index.htm; add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET,POST'; add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; }
2) If it is PNG, copy it directly; if not, convert it to PNG
3: write the navigator. Clipboard. Write
4: The complete code is as follows
`
convertToPng = imgBlob => { const imageUrl = window.URL.createObjectURL(imgBlob); const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); const imageEl = createImage({ src: imageUrl }); imageEl.onload = e => { canvas.width = e.target.width; canvas.height = e.target.height; ctx.drawImage(e.target, 0, 0, e.target.width, e.target.height); canvas.toBlob(copyToClipboard, "image/png", 1); }; }; createImage = options => { options = options || {}; const img = Image ? new Image() : document.createElement("img"); if (options.src) { img.src = options.src; } return img; }; // text createTextBlob = text => {return new Blob([text], {type: "text/plain"}); }; copyToClipboard = pngBlob => { console.log(pngBlob); // const textBlob = createTextBlob(" hello 222"); try { navigator.clipboard.write([ new ClipboardItem({ [pngBlob.type]: pngBlob, // [textBlob.type]: textBlob }) ]); console.log("Image copied"); } catch (error) { console.error(error); }}; / / copy pictures copyImg (" https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1089874897, & FM = 26 & gp = 0. 1268118658 JPG "); </script>`Copy the code