I\'m trying to programmatically use the execCommand in Chrome (Build 43) to copy the result of an asynchronous JSONP request to the clipboard. Here is a snippet of the logic
This is working timeout approach based on your snippet:
HTML:
<div id="container">
Enter Text To Copy</br>
<textarea id="clipboard"></textarea>
</div>
<input type="button" value="Copy" id="copy"/>
JS:
var timeout = 600; // timeout based on ajax response time
var loaded = false;
function loadContent() {
loaded = false;
$.getJSON('http://codepen.io/gkohen/pen/QbvoQW.js',function(result){
document.getElementById("clipboard").value = result.lorem;
loaded = true;
});
}
// Copy text as text
function copy() {
clipboard = document.getElementById("clipboard");
if (!loaded || clipboard.value.length == 0) {
alert("Ajax timeout! TIP: Try to increase timeout value.");
return;
}
clipboard.focus();
clipboard.select();
if (document.execCommand('Copy'))
alert("Successfuly coppied to clipboard!");
// set defaults
clipboard.value = "";
loaded = false;
}
document.addEventListener("DOMContentLoaded", function(){
document.getElementById("copy").onmousedown = loadContent;
document.getElementById("copy").onclick = function() {
setTimeout(copy, timeout); // wait for ajax
}
});
The main issue is execCommand specification. There are some restrictions about security and trusted actions. So you have to make event calling copy and ajax call aparte. This can be done dirty way - by fixed timeout (code above) or proper way - by breakable sleep. New sleep feature is mentioned here and maybe can be modified to breakable variant via clearTimeout, but I did not try.