Search code examples
javascriptjqueryclipboard

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>


Solution

  • 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>