I want to copy a card number into the clipboard so that I can paste it in Notepad. The code which I got from the internet works very well if tried in the developer toolbar of the browser. However if I add that code into my Javascript file and run the project then it does not work. Following is the code:
$.ajax({
type: "POST",
url: '@Url.Action("CopyToClipboard", "MyAccountSurface")',
data: {
controlId: controlId
},
dataType: 'json',
success: function(data) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val(data.CardNumber).select();
document.execCommand("copy");
$temp.remove();
alert('copied successfully');
}
});
Well, what are you copying?
document.execCommand("copy");
requires something to be selected(highlighted) in the first place.I think in your example,
select
follows .val(). But in order for this to work you need to be selecting an element, not it's value.If you want to copy into clipboard on click with Ajax
Element, which you are going to click has few events: mousedown and click. And they are triggered in this order. It means that you can send ajax request in first one and work with result in last one and in this case you will not have security problems.
Let me share working example:
You need this timeout with 100ms to wait for ajax response. It can be improved like you want.
Fixed and negative position - I think you know why we need it.
What @Anton said was good but it is all bad practice because You are depending on the server to give You a response at a given time which is bad, You can see in all the big websites that have complicated backend that they just put it in an HTML object so the user could copy it via ctrl+c or via button click, I would've done it a lil bit differently than Antons way
this way You dont need to reuse event listeners, yet like I said before its far from perfect. Better put it in a HTML element shown to the user.
As this is not a user interaction, it will not work.
The workarounds which we can implement is getting the data from the ajax call as soon as the mouseenter in the area where user wants to copy the data & place the data in some textarea or input box.
And, on the click event we can copy the data in the clipboard.
//mouseenter event of a button
// click event fired by user
Updated:
User interaction is mandatory to execute
document.execCommand
. So in your case it is not possible to copy the text from AJAX Response.It is the security measure that browsers agreed upon.
Refer W3C API
A workaround with user interaction
Steps added:
document.execCommand
since you are directly interacting with browser (Hence no security issue as mentioned in API
)ajax call and copying response need to be handled separately (for e.g click and mousedown events have been handled here).
setTimeout can be recursively used to check for response. Once response is received, copy to clipboard can be executed.