I am having trouble with execCommand('paste');
My code:
var copy = document.createElement("BUTTON");
copy.innerText = "Copy";
Sections.contextmenu.appendChild(copy);
copy.addEventListener("click", function(e) {
document.execCommand("copy");
});
var paste = document.createElement("BUTTON");
Sections.contextmenu.appendChild(paste);
paste.innerText = "Paste";
paste.addEventListener("click", function(e) {
console.log("Paste");
if (document.execCommand("paste")) {
console.log("pasted");
}
});
Copy worked right out of the box. I cannot get paste to work. I see "Paste" in the console, but nothing is pasted. I've read some things that say that this functionality needs to be explicitly turned on in Firefox. Is there no way (other than using flash... This is talked about in the research I've done) to execute "paste" in a content-editable element programmatically?
The paste command is disabled in web content (it’s only available in a browser extension). It’s disabled presumably because it would allow any website to steal the clipboard’s content. From the MDN documentation on execCommand:
paste
Pastes the clipboard contents at the insertion point (replaces current selection). Disabled for web content.
try the following code
console.log(document.exeCommand('paste')
If false maybe you need a permission to use it or your navigator can't support it
You can also use the Clipboard API, which would obliterate the exeCommand
Related
I'm having a hard time finding any recent info on how to add a listener for "Ctrl+C", fetching clipboard data, and then writing back to clipboard all in a Chrome Extension. All of the old code that i found was for the older versions that are now deprecated.
Basically you can manipulate clipboard using document.execCommand('paste|copy|cut').
You'll need to specify "clipboardWrite" and/or "clipboardRead" permissions in manifest.
"clipboardRead" Required if the extension or app uses document.execCommand('paste').
"clipboardWrite" Indicates the extension or app uses document.execCommand('copy') or document.execCommand('cut'). This permission is required for hosted apps; it's recommended for extensions and packaged apps.
Create <input> element (or <textarea>)
Put focus to it
Call document.execCommand('paste')
Grab you string from <input> value attribute.
This worked for me to copy data to clipboard.
In order to read Clipboard text in a chrome extension, you have to:
request "clipboardRead" permission in your manifest
create a background script, since only the background script can access the clipboard
create an element in your background page to accept the clipboard paste action. If you make this a textarea, you will get plain-text, if you make it a div with contentEditable=true, you will get Formatted HTML
if you want to pass the clipboard data back to an in page script, you'll need to use the message-passing API
To see an example of this all working, see 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;
Here is a very simple solution. All it requires is for your permissions to include "clipboardRead" and "clipboardWrite". The copyTextToClipboard function is taken from here: https://stackoverflow.com/a/18455088/4204557
var t = document.createElement("input");
document.body.appendChild(t);
t.focus();
document.execCommand("paste");
var clipboardText = t.value; //this is your clipboard data
copyTextToClipboard("Hi" + clipboardText); //prepends "Hi" to the clipboard text
document.body.removeChild(t);
Note that document.execCommand("paste") is disabled in Chrome, and will only work in a Chrome extension, not in a web page.
Best workable examples I found are here
below example worked for me, sharing here so that someone can get help
function getClipboard() {
var result = null;
var textarea = document.getElementById('ta');
textarea.value = '';
textarea.select();
if (document.execCommand('paste')) {
result = textarea.value;
} else {
console.log('failed to get clipboard content');
}
textarea.value = '';
return result;
}
I would like to hover my mouse on a URL and copy the URL with CTRL+Alt+C. This topic pretty much describes 99% of what I'm trying to do:
https://www.autohotkey.com/board/topic/111762-mouse-hover-copy-link/?p=662644
I've taken the userscript and modified it slightly, so that it gives me the URL after the "href" part. By the way, I'm not at all proficient with Javascript, I've simply played around with it and was lucky to get it working. Here's what I have:
This works great, but this copies the URL everytime I hover my mouse on a link. I don't want this, as it just adds a bunch of URLs to my clipboard.
At the bottom of that post, there's a Autohotkey component. It gets the tab title, rather than the URL.
How can I modify both the userscript and the Autohotkey to do what I want?
As a secondary question - I would like to create an additional userscript using the Javascript above as a reference. This new userscript will take the URL that my mouse is hovering on, change it so that it is prefixed with word:ofe|u| and pastes that into the URL bar when I click on the link while holding the Alt key. So basically:
Hover mouse on a URL that I am interested in (e.g. https www.google.com)
Userscript will modify the URL and change it to word:ofe|u|https://www.google.com
Hold down Alt + left click on the URL
word:ofe|u|https://www.google.com - page is loaded, or URL is pasted into the URL bar
UPDATE:
I've managed to get something going, not sure how I did it but I just played around with the codes I found on Google. Again, I do not know anything about Javascript.
https://pastebin.com/S9znPxBU
// ...
This works well, but if you do single press of CTRL+C, it just keeps copying URLs to the clipboard whenever you hover your mouse on a link. I want it to only start copying a URL to the clipboard everytime I press CTRL+C.
AutoHotkey won't help much here, as it can't access the URL directly. Thankfully, you can use the new JavaScript Clipboard API. It only works in secure contexts (AKA HTTPS) and the page needs to be in focus. Doing this using a browser extension would be perferred, since it can workaround those restrictions.
Try it, but first click on a blank area in the preview window to focus it.
// Userscript
"use strict";
window.addEventListener("load", () => {
const evOpts = {capture: true, passive: true};
let hoveredLink = null;
for (let link of document.getElementsByTagName("a")) {
link.addEventListener("mouseenter", () => {
hoveredLink = link;
}, evOpts);
link.addEventListener("mouseleave", () => {
hoveredLink = null;
}, evOpts);
}
window.addEventListener("keydown", (ev) => {
if (hoveredLink && ev.ctrlKey && ev.altKey && ev.code === "KeyC") // Ctrl+Alt+C
// Copy *absolute* URL to the clipboard
navigator.clipboard.writeText(new URL(hoveredLink.href, location.href)).then(()=>{
console.log("URL copied to clipboard!");
}, (err)=>{
console.error("Error copying URL to clipboard: ", err);
});
}, evOpts);
});
Google Youtube
I'm having a hard time finding any recent info on how to add a listener for "Ctrl+C", fetching clipboard data, and then writing back to clipboard all in a Chrome Extension. All of the old code that i found was for the older versions that are now deprecated.
Basically you can manipulate clipboard using document.execCommand('paste|copy|cut').
You'll need to specify "clipboardWrite" and/or "clipboardRead" permissions in manifest.
"clipboardRead" Required if the extension or app uses document.execCommand('paste').
"clipboardWrite" Indicates the extension or app uses document.execCommand('copy') or document.execCommand('cut'). This permission is required for hosted apps; it's recommended for extensions and packaged apps.
Create <input> element (or <textarea>)
Put focus to it
Call document.execCommand('paste')
Grab you string from <input> value attribute.
This worked for me to copy data to clipboard.
In order to read Clipboard text in a chrome extension, you have to:
request "clipboardRead" permission in your manifest
create a background script, since only the background script can access the clipboard
create an element in your background page to accept the clipboard paste action. If you make this a textarea, you will get plain-text, if you make it a div with contentEditable=true, you will get Formatted HTML
if you want to pass the clipboard data back to an in page script, you'll need to use the message-passing API
To see an example of this all working, see 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;
Here is a very simple solution. All it requires is for your permissions to include "clipboardRead" and "clipboardWrite". The copyTextToClipboard function is taken from here: https://stackoverflow.com/a/18455088/4204557
var t = document.createElement("input");
document.body.appendChild(t);
t.focus();
document.execCommand("paste");
var clipboardText = t.value; //this is your clipboard data
copyTextToClipboard("Hi" + clipboardText); //prepends "Hi" to the clipboard text
document.body.removeChild(t);
Note that document.execCommand("paste") is disabled in Chrome, and will only work in a Chrome extension, not in a web page.
Best workable examples I found are here
below example worked for me, sharing here so that someone can get help
function getClipboard() {
var result = null;
var textarea = document.getElementById('ta');
textarea.value = '';
textarea.select();
if (document.execCommand('paste')) {
result = textarea.value;
} else {
console.log('failed to get clipboard content');
}
textarea.value = '';
return result;
}
I have TinyMCE 4.0 in the page and when I select the text and try to paste it via CTRL+V, I get an error message saying that "Clipboard access not possible." This happens in IE8/9. However the same works fine in Chrome. Is there any workaround for this to get this working in IE?
Bounty:
I've tried resetting all IE settings (via Internet Options->Advanced->Reset All...) on two different computers, both running IE9, and one has the problem while the other does not.
Ultimately, I need to be able to paste formatted text (often with bullets or numeric lists and such) into TinyMCE and have it format them correctly. For this, I'm using the paste plugin, which seems to be throwing the error.
It seems to me that you're using an older TinyMCE 4 version, so in my opinion you should first do an upgrade to the latest version (4.0.3).
I've checked the source code of such version and I've found no trace of the Clipboard access not possible error message, which seems instead to be present in an earlier version of the tinymce/plugins/paste/plugin.min.js file, and only for Internet Explorer:
e.ie ? o.on("init", function () {
var e = o.dom;
o.dom.bind(o.getBody(), "paste", function (n) {
var r;
if (n.preventDefault(), a() && e.doc.dataTransfer)
return c(e.doc.dataTransfer.getData("Text")), t;
var i = u();
e.bind(i, "paste", function (e) {
e.stopPropagation(), r = !0
});
var s = o.selection.getRng(),
f = e.doc.body.createTextRange();
if (f.moveToElementText(i.firstChild), f.execCommand("Paste"), d(), !r)
return o.windowManager.alert("Clipboard access not possible."), t;
var p = i.firstChild.innerHTML;
o.selection.setRng(s), l(p)
})
}
Not being able to find an unminified version of this script, I can't say why such code fails, nor can I explain why it works only on one of your's computers.
In Internet Explorer's Tools menu, choose Internet Options.
Click the Security tab.
Click Trusted Sites.
Click the Sites... button.
Type your domain name (for example, widgetdesigns.com) in the first field, then click Add.
Unselect the checkbox that says Require server verification (https:) for all sites in this zone.
Click OK to apply your change.
Back on the Security tab, confirm that Trusted Sites is still selected, then click the Custom Level button.
Scroll down the Security section (near the bottom) and check the Disable box below Allow Programmatic clipboard access. (Checking this box will disable the access alert only for sites in your Trusted Sites list.)
Click OK then OK again to apply your changes.
What about this? Does this work?
I am working on a site where the client has a coupon code image on a product page and when the user clicks on the image he wants that code copied to the clipboard... is this possible?
With JavaScript clipboard access is pretty much disabled in all browsers unless a user enables it in their settings. The work around is using a Flash Copy to clipboard script, but Flash is getting more security restrictions set on that. Check out zeroclipboard.
If you want the image to be copied, you can use "createControlRange()" like so:
var imageTag = document.getElementById("couponCode");
if (document.body.createControlRange) //to check if browser is IE
{
var couponRange;
document.getElementById("couponCode").contentEditable = true;
couponRange = document.body.createControlRange();
couponRange.addElement(imageTag);
couponRange.execCommand('Copy');
document.getElementById("couponCode").contentEditable = false;
alert("Image copied");
}
else //for other browsers
{
alert("Your browser does not allow access to clipboard.\nPlease press Ctrl+C to copy");
var couponRange = document.createRange();
couponRange.selectNode(imageTag);
window.getSelection().removeAllRanges();
window.getSelection().addRange(couponRange);
}
Browsers other than IE do not allow Javascript to access the clipboard for security reasons. But you can invoke the browser functionality by asking the user to press Ctrl+C after selecting the range of the coupon image.
Hope this solves your problem.