I am working in a code that add some informations to a copied item in the clipboard. And besides, I'm also working to avoid that this function don't work when the selected text be inside a textarea, but without success until now.
Take a look at the source. When I run it, the extra informations are added even when the text inside the textarea is selected and copied. The intention is that extra info don't be added to the copied text inside the clipboard when the selected text be inside a textarea.
Is there anything wrong in my code?
Important: it doesn't work in Mozilla Firefox.
function addLink() {
/* The intention is that extra info don't be added to the copied text when the selected text be inside a textarea */
if (window.getSelection().baseNode.parentNode.tagName === 'TEXTAREA') return;
var selection = window.getSelection();
pagelink = "<br/></br/>Full text: " + document.title + "<br/>" + document.location.href;
copytext = ("“"+selection+"”") + pagelink;
newdiv = document.createElement('div');
newdiv.style.position = 'absolute';
newdiv.style.left = '-99999px';
document.body.appendChild(newdiv);
newdiv.innerHTML = copytext;
selection.selectAllChildren(newdiv);
window.setTimeout(function (){document.body.removeChild(newdiv);}, 100);
}
document.addEventListener('copy', addLink);
<b>It'll be added some extra info to whatever text copied inside this MRE, but the intention is that they don't be added when the selected text be inside a textarea.</b>
<p>When this text is copied, some informations are added to the clipboard.</p>
<p>Here too, but... </p>
<p><textarea id="urlCopied" rows="3" cols="30">how to avoid that extra informations be added when the copied text come from a textarea?</textarea></p>
<textarea placeholder="Paste for testing..." cols="40" rows="7"></textarea>
Related
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<textarea id="source" cols="100" rows="20"></textarea>
</form>
<script type="text/javascript">
var txarea = document.getElementById('source');
txarea.addEventListener('paste', function(){
let text = txarea.value;
console.log(text);
let replace_text = text.replace(/\n/g, ' ')
console.log(replace_text);
txarea.value = replace_text;
});
</script>
</body>
</html>
Copy some text with line break \n, for example
abc
ef
Then repeat: Control + A + Control + V. Then you can see there are more and more texts coming up each time.
I tried to add a debugger and check what's going on. But after I step over the last statement, it just becomes a mess.
What's wrong?
Lets break down the test case and how it interacts with your code.
User selects all text in the text area.
User initiates a "paste".
Before the paste takes place, your callback fires.
Your callback replaces the contents of the textarea with new, modified contents. (Replacing newlines with spaces.)
Because you have entirely replaced the textarea's contents with new contents, the user's initial text selection is no longer valid. So the effective cursor position is now at the end of the new, replaced contents.
The paste happens, adding new text to the end of the textarea's contents.
In step #5, if the text wasn't modified (i.e. it didn't have newlines to begin with) then the selection remains valid and the paste happens as a replace instead of an append.
I think that what you are trying to do is this:
Detect that the user is attempting to paste some text.
Modify the text before it gets pasted in. (By replacing newlines with spaces.)
You can find out what text is being pasted in using the paste event, i.e.:
let paste = (event.clipboardData || window.clipboardData).getData('text');
But you don't want to just replace the contents of the textarea with this pasted info, nor do you want to append it at the end. What if the user places the caret in the middle of the text and then hits ctrl+v?
Enter document.execCommand.
var txarea = document.getElementById('source');
txarea.addEventListener('paste', function(e) {
e.preventDefault();
let text = '';
if (e.clipboardData || e.originalEvent.clipboardData) {
text = (e.originalEvent || e).clipboardData.getData('text/plain');
} else if (window.clipboardData) {
text = window.clipboardData.getData('Text');
}
console.log(text);
let replace_text = text.replace(/\n/g, ' ');
console.log(replace_text);
if (document.queryCommandSupported('insertText')) {
document.execCommand('insertText', false, replace_text);
} else {
document.execCommand('paste', false, replace_text);
}
});
<form>
<textarea id="source" cols="100" rows="20"></textarea>
</form>
Note: Firefox does not (at the time of writing) support 'insertText' or 'paste' commands on a textarea or input (bug report 1220696), but it does support these commands on a contenteditable div.
I need to create a script that copy to clipboard's users (from any devices/OS/browser) a specific text.
I've found this library for JS ZeroClipboard. But I'am not so good in javascript, so my question is how to use this library in my script that is more or less like this.
<p id="text">text to copy</p>
<button onclick="CopyToClipboard()">Copy</button>
<script>
function CopyToClipboard(){
What i put here?
};
</script>
Help for using zeroclipboard or any other simpler way to do this?
It would be nice if it can work for most devices as possible! Thanks a lot!!!
I added comment to explain what's happening.
function CopyToClipboard() {
// Get the desired text to copy
var selectText = document.getElementById('text').innerHTML;
// Create an input
var input = document.createElement('input');
// Set it's value to the text to copy, the input type doesn't matter
input.value = selectText;
// add it to the document
document.body.appendChild(input);
// call select(); on input which performs a user like selection
input.select();
// execute the copy command, this is why we add the input to the document
document.execCommand("copy");
// remove the input from the document
document.body.removeChild(input);
}
<p id="text">text to copy</p>
<button onclick="CopyToClipboard()">Copy</button>
I think this is what you are looking for. No need to use a plugin for something as simple as you want. There is a method that lets you copy text 'execCommand("copy");'.
function myFunction() {
var copyText = document.getElementById("myInput");
copyText.select();
document.execCommand("copy");
alert("Copied the text: " + copyText.value);
}
<input type="text" value="This text is still being copied" style="display:none;" id="myInput">
<button onclick="myFunction()">Copy text</button>
If you want to copy static text from the p tag or div tag use below code..
var selectText = document.getElementById('text');
var range = document.createRange();
range.selectNode(selectText);
window.getSelection().addRange(range);
document.execCommand('Copy');
window.getSelection().removeAllRanges();
which means here you create the range for your text and select the node.
After that get the selection from that range.
Finally exec the command Copy and clear the ranges.
If you want to copy the text from input box use below..
var selectText = document.getElementById('text');
selectText.select();
document.execCommand("copy");
I've been trying to copy the innerContent of a <span> to my clipboard without success:
HTML
<span id="pwd_spn" class="password-span"></span>
JavaScript
Function Call
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('copy').addEventListener('click', copy_password);
});
Function
function copy_password() {
var copyText = document.getElementById("pwd_spn").select();
document.execCommand("Copy");
}
I've also tried:
function copy_password() {
var copyText = document.getElementById("pwd_spn").textContent;
copyText.select();
document.execCommand("Copy");
}
It seems like .select() doesn't work on a <span> element since I get the following error on both:
You could do this: create a temporary text area and append it to the page, then add the content of the span element to the text area, copy the value from the text area and remove the text area.
Because of some security restrictions you can only execute the Copy command if the user interacted with the page, so you have to add a button and copy the text after the user clicks on the button.
document.getElementById("cp_btn").addEventListener("click", copy_password);
function copy_password() {
var copyText = document.getElementById("pwd_spn");
var textArea = document.createElement("textarea");
textArea.value = copyText.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
textArea.remove();
}
<span id="pwd_spn" class="password-span">Test</span>
<button id="cp_btn">Copy</button>
See https://stackoverflow.com/a/48020189/2240670 there is a snippet of code for that gives you an example for a div, that also applies to a span, I did not copy it here to avoid duplication.
Basically, when you are copying to clipboard you need to create a selection of text, <textarea> and <input> elements make this easy because they have a select() method, but if you are trying to copy contents from any other type of element like a <div> or <span>, you'll need to:
Create/get a Range object(some browsers do not provide a constructor, or a decent way to do this). Calling document.getSelection().getRangeAt(0), I found works on most browsers except edge(ie11 works though).
Add the element you want to copy from to that range's selection.
Add that range to the window or document Selection.
Call document.execCommand("copy") to copy the selected text.
I also recommend checking the API of Selection and Range, that will give you a better grasp of this.
simple method
1)create a input
2)give style z-index -1 and it will be hide
var code = $("#copy-to-clipboard-input");
var btnCopy = $("#btn-copy");
btnCopy.on("click", function () {
code.select();
document.execCommand("copy");
});
<input type="input" style="width:10px; position:absolute; z-index: -100 !important;" value="hello" id="copy-to-clipboard-input">
<button class="btn btn-success" id="btn-copy">Copy</button>
I have text in contenteditable div and user can copy some its parts and paste inside this div. But there are styles coping with text, so i need to take copied part and take just text from it, so i'm making
<div id="text-container" contenteditable ng-paste="textPaste($event)"></div>
and js:
$scope.textPaste= function (e) {
var pasted_text = e.originalEvent.clipboardData.getData('text/plain');
e.originalEvent.clipboardData.setData('text/plain', pasted_text);
};
So I really get the text I need to the variable pasted_text , but it's not pasted instead of origin text. Can anybody help me?
Possible solution: create detached DOM element, paste formatted text into it and then return its textContent property:
var phantomEl = document.createElement('div');
phantomEl.innerHTML = pasted_text;
var cleanText = phantomEl.textContent;
After this, you will have plain text in the cleanText variable.
That's it :) I have a div with the id #toCopy, and a button with the id #copy.
What's the best way to copy #toCopy content to clipboard when pressing #copy?
You can copy to clipboard almost in any browser from input elements only (elements that has .value property), but you can't from elements like <div>, <p>, <span>... (elements that has .innerHTML property).
But I use this trick to do so:
Create a temporary input element, say <textarea>
Copy innerHTML from <div> to the newly created <textarea>
Copy .value of <textarea> to clipboard
Remove the temporary <textarea> element we just created
function CopyToClipboard (containerid) {
// Create a new textarea element and give it id='temp_element'
const textarea = document.createElement('textarea')
textarea.id = 'temp_element'
// Optional step to make less noise on the page, if any!
textarea.style.height = 0
// Now append it to your page somewhere, I chose <body>
document.body.appendChild(textarea)
// Give our textarea a value of whatever inside the div of id=containerid
textarea.value = document.getElementById(containerid).innerText
// Now copy whatever inside the textarea to clipboard
const selector = document.querySelector('#temp_element')
selector.select()
document.execCommand('copy')
// Remove the textarea
document.body.removeChild(textarea)
}
<div id="to-copy">
This text will be copied to your clipboard when you click the button!
</div>
<button onClick="CopyToClipboard('to-copy')">Copy</button>
The same without id:
function copyClipboard(el, win){
var textarea,
parent;
if(!win || (win !== win.self) || (win !== win.window))
win = window;
textarea = document.createElement('textarea');
textarea.style.height = 0;
if(el.parentElement)
parent = el.parentElement;
else
parent = win.document;
parent.appendChild(textarea);
textarea.value = el.innerText;
textarea.select();
win.document.execCommand('copy');
parent.removeChild(textarea);
}
I didn't tested for different windows (iframes) though!
UPDATED ANSWER
Javascript was restricted from using the clipboard, early on.
but nowadays it supports copy/paste commands.
See documentation of mozilla and caniuse.com.
document.execCommand('paste')
make sure that you support browsers that don't.
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
http://caniuse.com/#search=command
Javascript is not allowed to use the clipboard, but other plugins like flash do have access.
How do I copy to the clipboard in JavaScript?