access clipboard value in javascript

You can access the clipboard value in JavaScript using the clipboard API, which is available in modern browsers. The following code shows how to use the document.execCommand() method to cut or copy a selected text into the clipboard:

index.tsx
// Cut the selected text into clipboard
document.execCommand("cut");

// Copy the selected text into clipboard
document.execCommand("copy");
141 chars
6 lines

To paste the content of the clipboard into a text field or a DIV element, you can use the document.getSelection() and document.createRange() methods as follows:

index.tsx
// Get the current selection
var selection = document.getSelection();

// Create a range object
var range = document.createRange();

// Place the cursor at the beginning of the text field or DIV
range.setStart(textField, 0);

// Delete any existing content
range.deleteContents();

// Insert the clipboard content into the text field or DIV
range.insertNode(document.createTextNode(selection));
395 chars
15 lines

Note that the clipboard API may not be supported in all browsers. In that case, you can use other libraries or plugins to access the clipboard value.

gistlibby LogSnag