Paste the string to a text box. Chrome Extension

痞子三分冷 提交于 2019-12-13 12:51:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!