I'm trying this function:
function copyToClipboard(str) {
const el = document.createElement('textarea');
el.textContent = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) :
false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
alert("Success");}
I've tried with el.value = str; too.
What am I doing wrong?
The document.execCommand has been deprecated but still accessible across web browsers
The navigator.clipboard API is an alternative navigator.clipboard
You pass in the text to be copied to the clipboard like so
navigator.clipboard.writeText(str_to_copy).then(success_callback, failure_callback);
Note that the tab must be active for this to work else you won’t have permissions to copy the clipboard
The API is asynchronous so you can use the .then callback to alert the user if copying the clipboard was successful or not. Check out the Can I Use for its availability across web browsers.
You are creating an element that will be appended to DOM for a split second, just to allow the execCommand("copy")... And that will "display" at left -9999px.
So why the el.setAttribute('readonly', ''); ?
Just remove it and try again. My guess is the el.select(); just doesn't work on a readonly element.
Disclaimer: I did test nothing. But from what I read, this is the only weird thing to mention. Else is to find a duplicate answer or mark it as unreproducible.
Use this way to copy the text to clipboard.
function copyToClipboradFunc() {
let copiedText = document.getElementById("copyMe");
copiedText.select();
copiedText.setSelectionRange(0, 99999);
document.execCommand("copy");
console.log("Copied the text: " + copiedText.value);
}
<input type="text" value="Amoos Check Console" id="copyMe">
<button onclick="copyToClipboradFunc()">Copy to Clipboard</button>
Minor edits in your code.
/*
YOUR CODE
*/
function copyToClipboard(str) {
const el = document.createElement('textarea');
el.textContent = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) :
false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
alert("Copy Text: " + str );}
<!-- YOUR CODE -->
<button onclick="copyToClipboard('Your Function Copied')">Copy ( Original Function )</button>
Well, after some research I found the solution. Thanks to #VLAZ and #a.mola I found out that execCommand is deprecated. So I started to look for alternatives. I found about the clipboard API on this page Using the Clipboard API, that's from https://developer.mozilla.org/, so we know that's serious business. Anyway, here's my working function:
function copyToClipboard(str) {
navigator.permissions.query({
name: "clipboard-write"
}).then(result => {
if (result.state == "granted") {
navigator.clipboard.writeText(str).then(function () {
alert("Enlace copiado con succeso!");
}, function () {
alert("No fue posible copiar el enlace.");
});
}
});
};
I am using this. navigator.clipboard doesnt work for http.
function CopyToClipBoard(textToCopy) {
var successMessage = 'Success! The text was copied to your clipboard';
var errorMessage = 'Oops! Copy to clipboard failed. ';
// navigator clipboard api needs a secure context (https)
if (navigator.clipboard && window.isSecureContext) {
// navigator clipboard api method'
navigator.clipboard.writeText(textToCopy).then(
function () {
/* clipboard successfully set */
console.log(successMessage)
},
function () {
/* clipboard write failed */
console.warn(errorMessage)
}
)
} else
if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
// text area method
var textarea = document.createElement("textarea");
textarea.value = textarea.textContent = textToCopy;
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
var selection = document.getSelection();
var range = document.createRange();
range.selectNode(textarea);
selection.removeAllRanges();
selection.addRange(range);
try {
var successful = document.execCommand('copy'); // Security exception may be thrown by some browsers.
var msg = successful ? console.log(successMessage) : console.warn(errorMessage);
}
catch (ex) {
console.warn(errorMessage, ex);
}
finally {
selection.removeAllRanges();
document.body.removeChild(textarea);
}
}
Related
I am using hadlerbars as the view engine for express and i want the text in the variable code to be copied to the clipboard i tried many solutions . This is my current code
function copyLink() {
var copytext = document.getElementById('alcslink').innerHTML
let code = copytext.split(":- ").pop() /*formatted */
code.select();
code.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
navigator.clipboard.writeText(code.value);
}
when i run this it gives me this error in the web console
TypeError: code.select is not a function
This is how I use it:
Note, it does not work in the snippet engine. You will need to add it to your code.
Sorry.
const writeToClipboard = async (txt) => {
const result = await navigator.permissions.query({ name: "clipboard-write" });
if (result.state == "granted" || result.state == "prompt") {
await navigator.clipboard.writeText(txt);
console.log('Copied to clipboard');
}
};
document.querySelector('button').addEventListener('click', async () => {
const el = document.querySelector('div');
await writeToClipboard(el.innerHTML);
});
<div>copy me</div>
<button>Click</button>
We are able to get a selection range via window.getSelection().
I'm wondering whether there is a way to subscribe to window.getSelection changes.
The only way which came to me is to use timeouts (which is obviously bad) or subscribe to each user's key \ mouse press event and track changes manually.
ANSWER UPD: You are able to use this library, I've published it, as there are no more suitable ones: https://github.com/xnimorz/selection-range-enhancer
Use the onselect event.
function logSelection(event) {
const log = document.getElementById('log');
const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
log.textContent = `You selected: ${selection}`;
}
const textarea = document.querySelector('textarea');
textarea.onselect = logSelection;
<textarea>Try selecting some text in this element.</textarea>
<p id="log"></p>
For specific cases such as span contenteditable, you can make a polyfill:
function logSelection() {
const log = document.getElementById('log');
const selection = window.getSelection();
log.textContent = `You selected: ${selection}`;
}
const span = document.querySelector('span');
var down = false;
span.onmousedown = () => { down = true };
span.onmouseup = () => { down = false };
span.onmousemove = () => {
if (down == true) {
logSelection();
}
};
<span contenteditable="true">Try selecting some text in this element.</span>
<p id="log"></p>
if Im undesrting in right way you want to know when user start selection on page you can use DOM onselectstart.
document.onselectstart = function() {
console.log("Selection started!");
};
more info MDN
I wanted to get the selected text onmouseup.
I also tried
setTimeout(() => {
var selectedData = contentWrapper.getSelection().toString();
alert(selectedData)
}, 1008)
html code
<iframe src="url"></iframe>
js code
var contentWrapper=document.getElementsByTagName("iframe")[0].contentDocument;
contentWrapper.body.addEventListener('mouseup', this.CheckSelections, false);
function CheckSelections() {
var selectedData = contentWrapper.getSelection().toString();
alert(selectedData)
}
This way it works in IE, Chrome & FF (testing on local), but I am not able to touch iframe here.
function showSelection() {
var selectedData = document.getSelection().toString();
alert(selectedData)
}
var contentWrapper;
function attachIF() {
if(location.href == "https://stacksnippets.net/js") return;
var ifr = document.createElement("iframe");
ifr.src="javascript:'"+ // Access is denied. Here on stackoverflow.com
"<script>window.onload=function(){"+
"document.write(\\'<script>if(document.domain)document.domain=\\\""+document.domain+"\\\";"+
"document.write(\""+parent.document.body.innerText+"\");"+
"<\\\\/script>\\');"+
"document.close();"+
"parent.contentWrapper = document;"+
"document.body.onmouseup=parent.CheckSelections;"+
"};<\/script>'";
document.body.appendChild(ifr);
}
function CheckSelections() {
var selectedData = contentWrapper.getSelection().toString();
alert(selectedData)
}
<body onmouseup="showSelection()" onload=attachIF()>
<iframe src="https://stacksnippets.net/js"></iframe>
Some text to be selected.
</body>
I have made a plugin for CKEditor, but it relies on the currently selected text.
In FF and Chrome I can use:
var selectedText = editor.getSelection().getNative();
but this doesn't work in IE and I only get [object Object]
Any suggestions?
This is what I use:
var mySelection = editor.getSelection();
if (CKEDITOR.env.ie) {
mySelection.unlock(true);
selectedText = mySelection.getNative().createRange().text;
} else {
selectedText = mySelection.getNative();
}
Use:
editor.getSelection().getSelectedText();
Or:
CKEDITOR.instances["txtTexto"].getSelection().getSelectedText()
"txtTexto" = ID of textarea tag
To those who want to prefill fields with a selection, just do it like that and safe yourself a long journey.
onShow: function() {
this.setValueOf( 'tab-id', 'field-id', editor.getSelection().getSelectedText().toString() );
},
Have a nice day!
In the newer versions of CKEDITOR, there seems to be a way easier method:
var selectedHTML = editor
.getSelectedHtml()
.getHtml(); //result: <p>test</p>
#TheApprentice
You put it like this:
( function(){
var getSelectedText = function(editor) {
var selectedText = '';
var selection = editor.getSelection();
if (selection.getType() == CKEDITOR.SELECTION_TEXT) {
if (CKEDITOR.env.ie) {
selection.unlock(true);
selectedText = selection.getNative().createRange().text;
} else {
selectedText = selection.getNative();
}
}
return(selectedText);
}
...
with a call like this:
onShow: function() {
// Get the element currently selected by the user
var editor = this.getParentEditor();
var selectedContent = getSelectedText(editor);
I am creating a Google chrome extension which can read the contents of clipboard.
But I am unable to get the documentation for this. I want to get the clipboard content as in IE's clipboard API.
In the manifest file i gave permissions to
clipboardRead and clipboardWrite.
I have created a function in Background page as below
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getClipData")
sendResponse({data: document.execCommand('paste')});
else
sendResponse({}); // snub them.
});
And in Content Script I am calling the function like this
chrome.extension.sendRequest({method: "getClipData"}, function(response) {
alert(response.data);
});
But this returns me undefined...
document.execCommand('paste') returns success or failure, not the contents of the clipboard.
The command triggers a paste action into the focused element in the background page. You have to create a TEXTAREA or DIV contentEditable=true in the background page and focus it to receive the paste content.
You can see an example of how to make this work in my BBCodePaste extension:
https://github.com/jeske/BBCodePaste
Here is one example of how to read the clipboard text in the background page:
bg = chrome.extension.getBackgroundPage(); // get the background page
bg.document.body.innerHTML= ""; // clear the background page
// add a DIV, contentEditable=true, to accept the paste action
var helperdiv = bg.document.createElement("div");
document.body.appendChild(helperdiv);
helperdiv.contentEditable = true;
// focus the helper div's content
var range = document.createRange();
range.selectNode(helperdiv);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
helperdiv.focus();
// trigger the paste action
bg.document.execCommand("Paste");
// read the clipboard contents from the helperdiv
var clipboardContents = helperdiv.innerHTML;
If you want plain-text instead of HTML, you can either use helperdiv.innerText, or you can switch to using a textarea. If you want to parse the HTML in some way, you can walk the HTML dom inside the DIV (again, see my BBCodePaste extension)
var str = document.execCommand('paste');
You will need to add the clipboardRead permission too.
We cant access clipboard from javascript instead IE for chrome and other browsers.
The hack for this is very simple: create own custom clipboard which store text on cut and from where we paste it directly
function copy(){
if (!window.x) {
x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
var mytext = x.Selector.getSelected();
document.getElementById("book").innerHTML =mytext;
}
function cut(){
if (!window.x) {
x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
var mytext = x.Selector.getSelected();
document.getElementById("book").innerHTML =mytext;
x.Selector.setSelected()="";
}
function paste()
{
var firstDivContent = document.getElementById('book');
var secondDivContent = document.getElementById('rte');
secondDivContent.innerHTML += firstDivContent.innerHTML;
rte.focus();
}
function clear()
{
document.getElementById('rte').innerHTML="";
rte.focus();
}
<button id="cut"onclick="cut();">Cut</button>
<button id="copy"onclick="copy();">Copy</button>
<button id="paste"onclick="paste();">Paste</button>
Working Div
<div id="rte" contenteditable="true" style="overflow:auto;padding:10px;height:80vh;border:2px solid black;" unselectable="off" ></div>
Own Clipboard(hack)
<div id="book" contenteditable="true"style="background-color:#555;color:white;"> </div>