user754730
user754730

Reputation: 1340

Summernote copy image

I haven't found anything about this anywhere. How can I copy a selected image into the clipboard? I have created a custom js that adds a button to the popover of the image which works fine but I'm stuck here:

$.extend($.summernote.plugins, {
        'imageCopy': function (context) {
            var self = this;
            var ui = $.summernote.ui,
            $editable = context.layoutInfo.editable,
            options = context.options,
            $editor = context.layoutInfo.editor,
            lang = options.langInfo,
            $note = context.layoutInfo.note;

            context.memo('button.imageCopy', function () {
                var button = ui.button({
                    contents: options.imageCopy.icon,
                    container: false,
                    tooltip: lang.imageCopy.tooltip,
                    click: function () {
                        var img = $($editable.data('target'));
                        console.log('copy image=' + img);
                    }
                });
                return button.render();
            });
        }
    });

So I don't really know how I can get the data from the currently selected image and put it into the clipboard.

Upvotes: 1

Views: 987

Answers (2)

Kashyap Kaki
Kashyap Kaki

Reputation: 141

Just referred Summernote docs and other stuff. what I understood is it is providing restoreTarget attribute for getting reference of the selected image. You can get the source of the image through that and copy it to clipboard using Clipboard API.

Here is the code that I've tried.

Upvotes: 2

Christopher
Christopher

Reputation: 3677

The snippet does not use a button but shows how to make use of the Clipboard API. Simply click on the image.

It will be blocked on iframes. The errormessage refers to https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-permissions-in-cross-origin-iframes which depends on the flags allowed for the snippets here.

Also type "image/jpeg" returns an error while "image/png" works.

img.onclick = ({ target }) => {
  fetch(target.src)
  .then(function(response) {
    return response.blob()
  })
  .then(function(blob) {
    navigator.clipboard.write( [new ClipboardItem({ [blob.type]: blob })]).then(
        function () {
          console.log("Yay");
        },
        function (error) {
          console.error(error);
        }
    );
  });
};
<img id="img" src="https://i.imgur.com/I6N0hf2.png" style="height: 100px;">

Upvotes: 1

Related Questions