0

I want to make a bookmarklet to save a string parsed from an Array and I'm looking for an easy way to save my const cp = 'text' into clipboard. Is there any solution for this problem? Thanks in advance :)

Karlan
  • 353
  • 1
  • 2
  • 10
Wojtek
  • 29
  • 3
  • Does this answer your question? [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Itay Aug 26 '20 at 07:48
  • Is this what you are looking for: https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript – srv236 Aug 26 '20 at 07:50

3 Answers3

0

Have a look around before posting. This is from the w3schools site. Lots of great explanations there. https://www.w3schools.com/howto/howto_js_copy_clipboard.asp

function myFunction() {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /*For mobile devices*/

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
Steve
  • 4,372
  • 26
  • 37
  • I just to want to copy plain string, not to create extra element – Wojtek Aug 26 '20 at 08:03
  • I believe you'll need to create an element then add to it, copy it, remove it. Its a security this. Have a look at this post: https://stackoverflow.com/a/33928558/5553768 – Steve Aug 26 '20 at 08:35
  • select() function is not working in the browser, with injected js via bookmarklet – Wojtek Aug 26 '20 at 09:12
0

I have used the following function to achieve this.

  const copyToClipboard = (e) => {
    const el = document.createElement('input')
    el.value = window.location // I need a string that was located in the url => you should use whatever value you need, and set the input value to that, obviously.
    el.id = 'url'
    el.style.position = 'fixed'
    el.style.left = '-1000px' // otherwise, sometimes, it creates an input element visible on the screen
    el.setAttribute('readonly', true) // to prevent mobile keyboard from popping up
    document.body.appendChild(el)
    el.select()
    document.execCommand('copy')
  }
Fronzie
  • 33
  • 6
  • Like I said I use a bookmarklet and its not possible to create a new element in new tab and copy it to clipboard. Just want to save my variable value in clipboard – Wojtek Aug 26 '20 at 08:04
0

You can create a function like this using copy event

const copyToClipboard = (text) => {
  document.addEventListener('copy', function(e) {
    e.clipboardData.setData('text/plain', text);
    e.preventDefault();
  });
  document.execCommand('copy');
}

This answer is also helpful.

elpmid
  • 872
  • 1
  • 6
  • 18