Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

html - Storing clipboard data into a variable with JavaScript and the Google Chrome API

I am wondering if it is possible to store the contents of the clipboard in a string variable.

The following source states that this is not possible using pure JS, but I was thinking hoping that the chrome API would make it possible. (I am developing a chrome extension).

There is a clipboardRead permission, which would lead you to believe that it is possible, but it's description is just:

Required if the extension or app uses document.execCommand('paste'). source

To clarify: I am not trying to copy data to the clipboard or paste data from it. I would like to store the contents of the clipboard into a variable without mutating the clipboard contents in any way.

To further clarify, I can not assume that the clipboard data happens to be sitting in info.selectionText at the time of the operation.

If it is not possible, than I will just have to live with it I suppose, but it seems like something that would be possible to do with an extension.


EDIT: The reason I want to store the value is because I need to utilize the clipboard to perform an operation, but I would like to restore its contents when I am done, so the user doesn't loose whatever used to be in there.

If I just paste the data into a text area and store it from there, then, when I go to put the data back, the user will loose any formatting that they had, which is much better than nothing, but is not optimal.

Also, is there a way that I could store that data, even if it is not a string, (an image for example)? A solution that allows me to do this would undoubtedly implicitly answer the above question as well, but is not necessary. I am primarily looking save string data and would prefer a way to keep the formatting.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There was an experimental clipboard api a while ago, I guess they removed it though. You could always paste the contents into a textarea/contenteditable and get it's value:

function getClipboard() {    
    var el = document.createElement('textarea');
    document.body.appendChild(el);
    el.focus();
    document.execCommand('paste');
    var value = el.value;
    document.body.removeChild(el)
    return value;
}
console.log(getClipboard());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...