document.execCommand copy命令无效或其他解决方案? [英] document.execCommand copy command does not work or other solution?

查看:3555
本文介绍了document.execCommand copy命令无效或其他解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做的是以编程方式从网页中选择所有文本然后复制它。 select all适用于 execCommand 但复制没有。

What I am doing is programmatically select all text from a webpage and then copy it. The select all works with execCommand but copy doesn't.

这是我的代码:

$.ajax({
    url: $('#url').val(),
    type: 'GET',
    success: function(res) {
        $('#result').html(res.responseText);
        $('#result').fadeIn('fast');


        $('#result').focus();
        $('#result').select();

        document.execCommand('selectall');

        // copy does not work ?
        document.execCommand('copy');

    }
});

以下是JsBin上的示例

Here is Example on JsBin

我也尝试过使用flash解决方案,例如 ZeroClipboard ,但似乎必须按下他们的flash对象/按钮显式来复制文本,而我想做 zeroclip.setText('what'); ,无需用户按按钮。

I also tried using flash solution such as ZeroClipboard, however it seems that one has to press their flash object/button explicitly to copy text whereas I wanted to do zeroclip.setText('whatever'); without user's pressing the button.

可以有谁告诉如何以编程方式复制文本?

Can anyone tell how to copy text programmatically?

推荐答案

复制命令曾在所有浏览器中受到保护,但IE(在其他浏览器中不起作用)。请求用户使用Ctrl + C是一种常见的解决方法。

The copy command used to be protected in all browsers but IE (it would not work in other browsers). Requesting the user use Ctrl+C was a common workaround.

从Firefox 41(2015年9月),Chrome 42(2015年4月)和Opera 29(2015年4月)开始从某些受信任(用户触发的)事件触发时,默认情况下,复制命令在大多数主流浏览器中都不可用,例如响应按钮点击时会触发的事件。

As of Firefox 41 (September 2015), Chrome 42 (April 2015) and Opera 29 (April 2015) this is no longer the case the copy command should be available by default in most major browsers when triggered from certain trusted (user-triggered) events, such as what would be fired in response to a button click.

兼容性表来自MDN,
和W3C 错误进一步提供信息。

The compatibility table from MDN, and W3C bug offer further information.

这篇关于document.execCommand copy命令无效或其他解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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