Paste an image from clipboard using JavaScript [duplicate] - javascript

This question already has answers here:
How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?
(3 answers)
Closed 3 years ago.
How do we paste an image from clipboard into a custom rich text editor using javascript? (ctrl+c and ctrl+v or a snapshot).
Has anyone used Ajax's rich text editor? Does pasting an image from clipboard to Ajax RTE work?

Because this question still often shows up in Google's search results, I want to point out this is possible today, at least in Google Chrome (2011) in all modern browsers (2018). They implemented it to use in GMail, but it is available for all websites.
How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?

To help others, I'll leave the link here with the answer made by Nick Rattalack
// window.addEventListener('paste', ... or
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items)); // will give you the mime types
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
reader.onload = function(event){
console.log(event.target.result)}; // data url!
reader.readAsDataURL(blob);
}
}
}
How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?

This is definitely possible now in Chrome and Firefox. I'm not so sure about IE/Safari.
Look at imgur.com, onpaste, and pasteboard.co as examples, and see the code for pasteboard on github as well as Joel's excellent write up on his blog
For the record, you need the user to press Ctrl+V on your element, and then you can capture the data in the paste event handler by reading from event.clipboardData but to make it work down-level, you need to be sure focus is on an empty contenteditable element, and pull the results from there, which doesn't work well in Firefox 22. See here

New browsers, like Firefox 4, support pasting of image data from clipboard into a RTE as Data URI with encoded PNG Data. However, most web applications incorrectly parse these Data URIs and discard it. Yahoo mail properly handles. However Gmail and Hotmail discard it. I have notified Google and Microsoft about this.

For now i found the clipboardData Object .
But it retrieve only text format or URL from clipboard.
clipboardData is IE only, it works with character string and return null if we paste an image.
a test example
<form>
<input type="text" id="context" onClick="paste();">
</form>
<script type="text/javascript">
function paste() {
var sRetrieveData = clipboardData.getData("Text");
document.getElementById('context').value = sRetrieveData;
}
</script>
By default clipboard access is not enabled on firefox, explanation here.
On the other way, execCommand() only process text values and is not Firefox compliant.
Like the others said, the fact that code works on IE is a security risk, any site can access your clipboard text.
The easiest way to copy images relative URL is to use a java applet, windows activeX plugin, .net code or drag and drop it.

Unfortunately, It's not possible to paste an image from your clipboard to the RTE.
If you copy a blob from a desktop app like Microsoft Word that contains an image and some text, the image will turn up as a broken reference (though the proportions will be correct) and the text will be pasted correctly (formatting will be lost).
The only thing that is possible is to copy an image within the RTE and paste back within the RTE.

Related

Is it possible to get copied file from explorer in javascript?

I have worked on a chat feature where the requirement is to get copied images on paste them from file explorer (like skype desktop). e.g I CTRL+C an image file then CTRL+V on Chat textarea.
But I get images only from the clipboard.
From file explorer, it is not working.
Here is a demo screenshot.
Try some of those https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard - either the new (and still somewhat experimental) navigator.clipboard api or the old document.execCommand function.

CKEditor Text fonts size gets changed on Copy of text from outlook [IE 11 ONLY]

I have a strange issue where in the fonts of the text gets changed while copying the text from outlook (desktop) to CKEditor.
All the fonts gets bigger than what is in the source.
This issue happens only in IE 11 and in Chrome it preserves the fonts fine.
I have tried several events to catch the text and do some formatting but this screws up the fonts in Chrome.
Any solution/suggestion welcome.
Content from MS Office is usually extra filtered by Paste From Word plugin. By design this plugin should work for Word only (more info here), but sometimes when browser has better Clipboard API support it might work for other MS Office products (like Outlook). I suspect that in this case in Chrome data are filtered using mentioned plugin and are not filtered in IE11. This might be a reason of different content in editor for both cases.
To catch pasteddata and modify it before inserting to editor's content, you should use paste event. Example how to use it you can find below or under link: https://codepen.io/msamsel/pen/mqJPde?editors=1011
You can modify inserted data according to your needs. Actually Paste from Word is one big filter which detects data pasted from MS Word and applying filter or modifies excess things.
var editor = CKEDITOR.replace( 'editor' );
editor.on( 'paste', function( evt ) {
console.log( evt.data.dataValue ); // There is no additional paragraph yet.
evt.data.dataValue = '<p>Additional Paragraph</p>' + evt.data.dataValue; // Modify data pasted to editor.
} )

javascript execCommand("paste") not working

document.execCommand("Paste") doesn't work!
"Copy" and "cut" works fine.
var editor = document.getElementById("ta1");
editor.focus();
editor.select();
var successful = document.execCommand("Paste");
var msg = successful ? 'successful' : 'unsuccessful';
alert('Pasting text command was ' + msg);
This alerts "unsuccessful" on paste, but "successful" on copy and cut..
I use the "copy" another place on my webpage, and the whole thing works like a charm, but I need to get "paste" working as well..
I'm using Chrome (no extension, just a regular webpage).
Any ideas?
For security reason, it is blocked in chrome.
Even office 365 asks to their users to use shortcuts ctrl+c/ctrl+v instead of copy.
this function is only available for chrome extension now.
if the text you want to copy has to be paste on the same page then just store the text in a variable, you can then use the following command to paste
document.execCommand('insertText'
but you need to focus the textarea first
and to copy the selection https://developer.mozilla.org/fr/docs/Web/API/Window/getSelection
full example
https://jsfiddle.net/bormat/9a8nuzse/2/
This is clearly mentioned in Mozilla Documentation of Document.execCommand()
that:
paste
Pastes the clipboard contents at the insertion point (replaces current selection). Clipboard capability must be enabled in the user.js preference file. See 1.
1 Before Firefox 41, clipboard capability needed to be enabled in the user.js preference file. See A brief guide to Mozilla preferences for more information. If the command wasn't supported or enabled, execCommand was raising an exception instead of returning false.In Firefox 41 and later, clipboard capability are enabled by default in any event handler that is able to pop-up a window (semi-trusted scripts).
I had a same issue. hence as work around I used below code, its working with some limitation. give a try :)
navigator.clipboard.readText().then(function(text){
document.execCommand( "insertHTML", false, text || "");
});

the proper use of execcommand("paste") in a chrome extension

I'm trying to paste clipboard data into a textarea using execcommand("paste") with a chome extension, but i cannot seem to get it to work.
permissions are set.
I have tried to set focus() on the textarea, but document.execCommand("paste") does nothing, and I get no error.
calling execcommand("paste") from background page also does nothing.
<form>
<textarea id="ta"></textarea>
</form>
<script type="text/javascript">
document.findElemetById("ta").focus();
document.execCommand("paste");
</script>
Clipboard functionality is a key part of my extension so I've seen all the normal problems. On my background page I expose a copy and a paste function and the page itself contains <textarea id="sandbox"></textarea>;
function copy(str) {
var sandbox = $('#sandbox').val(str).select();
document.execCommand('copy');
sandbox.val('');
}
function paste() {
var result = '',
sandbox = $('#sandbox').val('').select();
if (document.execCommand('paste')) {
result = sandbox.val();
}
sandbox.val('');
return result;
}
I'm using jQuery for simplicity but you get the idea. Now any time I want to use the clipboard functionality I simply call the relevant function. Other pages in my extension can access this API via chrome.extension.getBackgroundPage() but you can also use chrome.runtime.getBackgroundPage(callback) if your background page is an event page.
I'm not sure if this is best practice or if such a thing even exists for this functionality yet but this definitely works for me and is very clean.
This is too long for a comment on Alasdair's excellent response, so I'm creating another answer. Alasdair's answer is excellent and worked great for me, but as a newcomer to Chrome extensions it still took me a while to get it working. For anyone in a similar position, here is an expansion on his answer.
Background/event pages are able to interact with the system clipboard, provided you've requested the appropriate permissions. They are not able to interact with the DOM of pages the user has loaded. Content scripts cannot interact with the system clipboard, but they can interact with the DOM of pages the user has loaded. Take a look at the explanation of the extension architecture for a good overview of all this.
This essentially means you need to do the copy/paste actions from the system clipboard in your event/background pages, which is what Alasdair has outlined above. Any pasting or copying from the DOM of the page the user is viewing has to occur in your content script. The two scripts are able to communicate pretty easily with message passing.
I have an extension whose only purpose is to paste, and the architecture came largely from this post. If you want to see the above technique in practice, take a look at the code. In particular, background.html, background.js, and contentscript.js.
If you're in a real hurry, here is a gist.
function PasteString() {
var editor = document.getElementById("TemplateSubPage");
editor.focus();
// editor.select();
document.execCommand('Paste');
}
function CopyString() {
var input = document.getElementById("TemplateSubPage");
input.focus();
// input..select();
document.execCommand('Copy');
if (document.selection) {
document.selection.empty();
} else if (window.getSelection) {
window.getSelection().removeAllRanges();
}
}
Hope this will work for you

Can I paste image data with JavaScript? [duplicate]

This question already has answers here:
How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?
(3 answers)
Closed 3 years ago.
How do we paste an image from clipboard into a custom rich text editor using javascript? (ctrl+c and ctrl+v or a snapshot).
Has anyone used Ajax's rich text editor? Does pasting an image from clipboard to Ajax RTE work?
Because this question still often shows up in Google's search results, I want to point out this is possible today, at least in Google Chrome (2011) in all modern browsers (2018). They implemented it to use in GMail, but it is available for all websites.
How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?
To help others, I'll leave the link here with the answer made by Nick Rattalack
// window.addEventListener('paste', ... or
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items)); // will give you the mime types
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
reader.onload = function(event){
console.log(event.target.result)}; // data url!
reader.readAsDataURL(blob);
}
}
}
How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?
This is definitely possible now in Chrome and Firefox. I'm not so sure about IE/Safari.
Look at imgur.com, onpaste, and pasteboard.co as examples, and see the code for pasteboard on github as well as Joel's excellent write up on his blog
For the record, you need the user to press Ctrl+V on your element, and then you can capture the data in the paste event handler by reading from event.clipboardData but to make it work down-level, you need to be sure focus is on an empty contenteditable element, and pull the results from there, which doesn't work well in Firefox 22. See here
New browsers, like Firefox 4, support pasting of image data from clipboard into a RTE as Data URI with encoded PNG Data. However, most web applications incorrectly parse these Data URIs and discard it. Yahoo mail properly handles. However Gmail and Hotmail discard it. I have notified Google and Microsoft about this.
For now i found the clipboardData Object .
But it retrieve only text format or URL from clipboard.
clipboardData is IE only, it works with character string and return null if we paste an image.
a test example
<form>
<input type="text" id="context" onClick="paste();">
</form>
<script type="text/javascript">
function paste() {
var sRetrieveData = clipboardData.getData("Text");
document.getElementById('context').value = sRetrieveData;
}
</script>
By default clipboard access is not enabled on firefox, explanation here.
On the other way, execCommand() only process text values and is not Firefox compliant.
Like the others said, the fact that code works on IE is a security risk, any site can access your clipboard text.
The easiest way to copy images relative URL is to use a java applet, windows activeX plugin, .net code or drag and drop it.
Unfortunately, It's not possible to paste an image from your clipboard to the RTE.
If you copy a blob from a desktop app like Microsoft Word that contains an image and some text, the image will turn up as a broken reference (though the proportions will be correct) and the text will be pasted correctly (formatting will be lost).
The only thing that is possible is to copy an image within the RTE and paste back within the RTE.

Categories

Resources