问题
I am making a chrome extension that requires copy and pasting text. Suppose a user selects some text on any webpage, it should be copied into a variable and when the user presses ctrl+3, (if in a textbox or somewhere where our normal ctrl+v works) it should paste it. A normal copy paste tool but with different shortcuts.
Currently my script has this function: I am retrieving the data correctly but don't know how to paste it.
var copy_paste1;
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 49 && evt.ctrlKey) {
var c = window.getSelection();
copy_paste1 = c
alert(copy_paste1);
document.getElementById("myButtonId").click();
}
if (evt.keyCode == 51 && evt.ctrlKey) {
alert(copy_paste1);
//****INSTEAD OF THIS ALERT I WANT TO PASTE!
}
};
How can I proceed?
回答1:
You could use document.activeElement to get the currently focused element, and then try to set it's value:
document.activeElement.value = copy_paste1;
This is, of course, the bare bones approach - it would be recommended to at least add some checks before simply trying to set the value (ie. check if type is textbox, textarea, etc.), but this should get you started.
来源:https://stackoverflow.com/questions/24895921/paste-the-string-to-a-text-box-chrome-extension