Reputation: 42418
I have an event listener which listens on ctrl - v
paste event. Inside the listener I use clipboardData.getData
method to get the copied data from clipboard. But now I need to implement a button when users click on that button it does the copy logic. My question is how to trigger a paste event programmatically. The main thing I need to get is the clipboardData
instance.
Below code is my current paste
event listener. I need to mock the e
paste event in order to make the button work.
myDom.on('paste',function(e) {
e.preventDefault();
var data = (e.originalEvent || e).clipboardData.getData('application/image');
});
Upvotes: 17
Views: 32720
Reputation: 618
window.clipboardData.getData('Text');
might work in some browsers, is some browser will prompt the user if they wish their clipboard data to be accessed.
Upvotes: 4
Reputation: 1073968
My question is how to trigger a paste event programmatically.
You can't, without the browser having a special setting allowing it (I'm not aware of one that does, and can't immediately find it in Firefox or Chrome's settings) and the user enabling that setting. If you could, it would be a significant security problem, because your web page could snoop on the contents of the user's clipboard. That's why you can only get clipboard data from an event object for a clipboard event.
From the specification:
11.1. Privacy and the Clipboard Event API
The Clipboard Event API allows scripts running in the context of a clipboard event handler to access a copy of the system clipboard and potentially modify the data being written to the clipboard.
User agents should be aware of the following requirements with regards to securing the data accessed by the Clipboard Event API:
Objects implementing the
DataTransfer
interface to return clipboard data must not be available outside the ClipboardEvent event handler that the data is provided to.If a script stores a reference to an object implementing the
DataTransfer
interface to use from outside the ClipboardEvent event handler, all methods must be no-ops when called outside the expected context.Implementations must not let scripts create synthetic clipboard events to get access to real clipboard data (unless the user has configured it to do so).
Even though the Clipboard Event API is not covered by the Clipboard permission, user agents may choose to provide a method for the user to disable this API or to configure which sites are allowed to access it.
(my emphasis on the third bullet point)
Note that the spec does say "unless the user has configured it to do so" but again, I'm not aware of a browser that lets the user do that. (Just whether web sites can see clipboard events at all.)
Upvotes: 14