Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting clipboard content as a string variable

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>
like image 289
qadenza Avatar asked Jan 11 '20 20:01

qadenza


2 Answers

You can't get the value of clipboard like this for 2 reasons :

  1. your function is asynchronus so when you call your function there is no 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.
  2. you can't call clipboard programmatically for security reason navigator don't allow you to access clipboard without user action with web page. That why only with click of button you have access to user clipboard.

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>
like image 184
Antoine Guerra Avatar answered Sep 22 '22 20:09

Antoine Guerra


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);


Try this code:
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);
}
like image 28
Alex Baban Avatar answered Sep 24 '22 20:09

Alex Baban