How can I copy text to the clipboard when copying an image?

I am creating a webpage and am faced with something that would be nice to do; set the text to be copied to the clipboard when someone is trying to copy the image, probably the same as the alt text. Is there a way with javascript / html that this can be done? If yes, please explain.

Thanks for any help!

Edit: Basically, I want my users to select an image, press control-c, and then save the text to their clipboard.

+8
source share
3 answers

I do not think you can. If you could connect keyboard events through the browser, that would be a huge security issue. You can capture keystrokes and send them to a web service in a few lines of code, which very easily spoils some lives.

You can detect the mouse event down using onmousedown, attaching it to the image in some way, and storing this alt text in a hidden field or cookie and DoSomething() from there.

+1
source

I have seen services like tynt do something like this. 2065880 Javascript: Hijack Copy? talks about methods, as well as 1203082 entering text when copying content from a web page

+1
source

This is possible because Twitch.tv does this when copying images of emotions in chat. The trick is to use the copy event .

 const parent = document.getElementById('parent'); parent.addEventListener('copy', event => { let selection = document.getSelection(), range = selection.getRangeAt(0), contents = range.cloneContents(), copiedText = ''; for (let node of contents.childNodes.values()) { if (node.nodeType === 3) { // text node copiedText += node.textContent; } else if (node.nodeType === 1 && node.nodeName === 'IMG') { copiedText += node.dataset.copyText; } } event.clipboardData.setData('text/plain', copiedText); event.preventDefault(); console.log('Text copied: '${copiedText}''); }); 
 #parent { display: flex; flex-direction: row; align-content: center; align-items: center; flex-grow: 0; } #parent, #pasteHere { padding: 0.5rem; border: 1px solid black; } .icon { width: 32px; } #pasteHere { margin-top: 1rem; background: #E7E7E7; } 
 <p>Copy the line below:</p> <div id="parent"> Some text <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg?v=f13ebeedfa9e" class="icon" data-copy-text="foo" /> some more text <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg?v=f13ebeedfa9e" class="icon" data-copy-text="bar" /> </div> <div id="pasteHere" contenteditable>Paste here!</div> 
0
source

All Articles