正确使用chrome扩展中的execcommand(“paste”) [英] the proper use of execcommand("paste") in a chrome extension

查看:2788
本文介绍了正确使用chrome扩展中的execcommand(“paste”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 execcommand(paste)将剪贴板数据粘贴到textarea中,但是我似乎无法使其工作。
权限已设置。
我试图在textarea上设置 focus(),但是 document.execCommand(paste)什么都不做,我也没有错。
从背景页面调用 execcommand(paste)也没有任何作用。

I'm trying to paste clipboard data into a textarea using execcommand("paste") with a chome extension, but i cannot seem to get it to work. permissions are set. I have tried to set focus() on the textarea, but document.execCommand("paste") does nothing, and I get no error. calling execcommand("paste") from background page also does nothing.

<form>
     <textarea id="ta"></textarea>    
</form>
<script type="text/javascript">
    document.findElemetById("ta").focus();
    document.execCommand("paste");
</script>


推荐答案

剪贴板功能是我的扩展程序,所以我已经看到了所有正常的问题。在我的背景页上,我公开了一个 copy 和一个粘贴函数,并且页面本身包含< ; textarea id =sandbox>< / textarea> ;

Clipboard functionality is a key part of my extension so I've seen all the normal problems. On my background page I expose a copy and a paste function and the page itself contains <textarea id="sandbox"></textarea>;

function copy(str) {
    var sandbox = $('#sandbox').val(str).select();
    document.execCommand('copy');
    sandbox.val('');
}

function paste() {
    var result = '',
        sandbox = $('#sandbox').val('').select();
    if (document.execCommand('paste')) {
        result = sandbox.val();
    }
    sandbox.val('');
    return result;
}

我正在使用 chrome.extension.getBackgroundPage()访问此API,但您也可以使用如果您的背景页是 chrome.runtime.getBackgroundPage(回调), /developer.chrome.com/extensions/event_pages\">事件页面。

I'm using jQuery for simplicity but you get the idea. Now any time I want to use the clipboard functionality I simply call the relevant function. Other pages in my extension can access this API via chrome.extension.getBackgroundPage() but you can also use chrome.runtime.getBackgroundPage(callback) if your background page is an event page.

我不确定这是最佳做法,还是甚至是这样的事情存在这种功能,但这绝对适用于我,非常干净。

I'm not sure if this is best practice or if such a thing even exists for this functionality yet but this definitely works for me and is very clean.

这篇关于正确使用chrome扩展中的execcommand(“paste”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆