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>