I want to copy/paste some content from one div to another
In the example below clicking on paste
button expected result in target
div is - <p>lorem ipsum</p>
but simply - nothing happens
$('.btncopy').on('click', function(){
let a = $('.story').html().trim();
navigator.clipboard.writeText(a);
console.log(a); // it works
});
$('.btnpaste').on('click', function(){
let a = navigator.clipboard.readText();
console.log(a); // doesn't work
$('.target').text(a);
});
.story, .target{min-height:25px; background:orange;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='btncopy'>COPY</button>
<button class='btnpAste'>PASTE</button>
<div class='story'><p>lorem ipsum</p></div>
<br>
<div class='target'></div>
CodePudding user response:
readText()
(just as writeText
) returns a Promise, you need to await for it. So in your case it will be something like this:
navigator.clipboard.readText().then(function(a) {
console.log(a); // works
$('.target').text(a);
});
However if you try it in the SO snippet runner (or any other JS fiddler online) it will not work due to permission restrictions.