When trigger copy event (cmd + c), our application needs to call and get data from web worker, and then set it to clipboard.
But after the data is ready, setting data to clipboard doesn’t seem to work.
async function process_copy(event) {
let data = await get_data_from_worker();
console.log("DATA FROM WORKER: ", data);
event.clipboardData.setData('text/plain', data);
event.clipboardData.setData('text/html', data);
event.preventDefault();
}
window.addEventListener('copy', process_copy.bind(this));
What I need is to set data to clipboard since the data from web worker is available for use.
The reason why I can’t use this command
document.execCommand('copy’)
Because time to get data from web worker may take more than 5 secs, and the command above doesn’t work in these cases.
Here is an example:
worker.js
onmessage = function(e) {
postMessage('WORKER DATA');
}
index.html
<!DOCTYPE html>
<html>
<body>
<script>
window.onload = function() {
const my_worker = new Worker("worker.js");
let call_back;
my_worker.onmessage = function(e) {
if(call_back){
call_back(e.data);
}
call_back = undefined;
}
function get_data_from_worker() {
return new Promise(
function(resolve, reject) {
call_back = resolve;
my_worker.postMessage("GET DATA");
}
)
}
async function process_copy(event) {
let data = await get_data_from_worker();
console.log("DATA FROM WORKER: ", data);
event.clipboardData.setData('text/plain', data);
event.clipboardData.setData('text/html', data);
event.preventDefault();
}
window.addEventListener('copy', process_copy.bind(this));
};
</script>
</body>
</html>
After users trigger the copy event, It calls to process_copy function, and waits for data.
In get_data_from_worker function, I have created a promise, which sends message to web worker, and then store resolve in call_back for later use.
When the web worker receive the message, it prepares data and send back, through postMessage method.
Then, the web worker message will be returned by call_back (inside my_worker.onmessage).
After that, the data is ready in process_copy function. But We can't set that data to clipboard.