There are two solutions that work, but both are erroneous. One works only if your request takes less than one second and one of them is out of date, so it cannot be used in a production environment.
First you need to use setTimeout , which is one of the few asynchronous functions that does not lose the execCommand privilege. But it does not lose if it is equal to or less than 1000 ms. Therefore, if your request is less than this, you should go, but if not, then , you have an error. If you combine it with some kind of timeout processing, it may work, but if requests often take more than 1 second, then this may not be enough. For example, for example:
var toCopy; const buttonClick = () => { setTimeout(function() { if (toCopy) { // strangely, this execCommand will work console.log(document.execCommand('copy')); } }, 1000); var client = new XMLHttpRequest(); client.onload = function(data) { toCopy = this.responseText; }; // by setting your timeout on your request // with the same duration as the setTiemout // you make sure it either works or throws an error client.ontimeout = function(data) { console.log('timeout'); }; client.timeout = 1000; client.open("GET", "https://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain"); client.send(); } $(() => { $("button").click(buttonClick) }) document.addEventListener('copy', function(e) { e.preventDefault(); e.clipboardData.setData('text/plain', toCopy); });
https://jsfiddle.net/8md4Ltu2/4/
There is another way to make it work, but it is deprecated, so it cannot be used. But to be careful, I will put it here. You can set the asynchronous flag of your XMLHttpRequest to false. The request will be synchronous, and processing execCommand will be very simple. But this synchronous flag is outdated, management should throw an error if you try to use it so that it is not used. See: https://xhr.spec.whatwg.org/#synchronous-flag
var toCopy; const buttonClick = () => { var client = new XMLHttpRequest(); client.onload = function(data) { toCopy = this.responseText; console.log(document.execCommand('copy')); }; client.open("GET", "https://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain", false); client.send(); } $(() => { $("button").click(buttonClick) }) document.addEventListener('copy', function(e) { e.preventDefault(); e.clipboardData.setData('text/plain', toCopy); });
https://jsfiddle.net/zezskm2x/2/