Trying to get clipboard content as a string variable (for example page url is copied);
The code below returns undefined
in console.
function get_clip(){
navigator.clipboard.readText().then(text => {return text;})
.catch(err => {console.error('Failed to read clipboard contents: ', err);});
}
var str = get_clip();
console.log(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can't get the value of clipboard like this for 2 reasons :
return
called, your value is equal to undefined. You can use
callBack function passed in params of get_clip
func to do your job
with your result.function get_clip(callBack) {
navigator.clipboard.readText()
.then(text => {
callBack(text);
})
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
}
let callback = function(str) {
console.log(str);
};
document.querySelector('#showClipboard').addEventListener('click', function() {
get_clip(callback);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="showClipboard">click me to show clipboard</button>
That is because it takes time to execute get_clip()
, it takes time to read the clipboard (imagine you could have a huge amount of text in the clipboard), and the JavaScript engine does not stop but instead executes the next line and logs 'undefined'.
Asynchronous JavaScript: (https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing)
So, what you can do is tell get_clip()
what to do when is done reading the clipboard. You can say to get_clip()
, execute this function aCallback
with something like this:
var str = get_clip(aCallback);
function get_clip(callback) {
navigator.clipboard.readText()
.then(text => { return callback(text); })
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
}
var str = get_clip(aCallback);
function aCallback(text) {
console.log(text);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With