Copy image to clipboard from Chrome app (not for extension or page)

I am trying to copy an image to the clipboard from my Chrome application. Please keep in mind that I specifically ask about new Chrome applications (formerly called Chrome Packaged Apps) not from the Chrome extension or from a regular web page in Chrome.

I asked for permission of "clipboardWrite" and "clipboardRead" in manifest.json

"permissions": [
    {"fileSystem": ["write", "retainEntries", "directory"]}, 
    "https://www.google-analytics.com/",
    "storage",
    "clipboardWrite",
    "clipboardRead"
],

Based on the related “copy image to clipboard” questions here at StackOverflow, I tried 4 different approaches.

function onClickButton() {
    document.oncopy = function(event) {
        var dataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAIAAAA7ljmRAAAAGElEQVQIW2P4DwcMDAxAfBvMAhEQMYgcACEHG8ELxtbPAAAAAElFTkSuQmCC";
        // base64 decode the data url, skipping the data url prefix 
        var data = atob(dataURL.substring("data:image/png;base64,".length));
        // copy the decoded data to an binary array 
        var dataArray = new Uint8Array(data.length);
        for (var i = 0; i < data.length; i++) {
            dataArray[i] = data.charCodeAt(i);
        }

        // approach 1 - failed, pastes nothing
        event.clipboardData.setData('image/png', dataArray);

        // approach 2 - failed, pastes nothing
        event.clipboardData.setData('text/uri-list', dataURL);

        // approach 3 - failed, ends up pasting the text "image.png"
        var file = new File(dataArray, "image.png", {type: "image/png"});
        event.clipboardData.items.add(file);

        // approach 4 - failed, pastes nothing
        event.clipboardData.items.add(dataURL, 'text/uri-list');

        event.preventDefault();
    };
    document.execCommand("Copy");
}

4 . , ? FYI, 1 "text/plain" . , , , API, - .

+4

Source: https://habr.com/ru/post/1627521/


All Articles