~Onlooker 2008-12-30 13:09 采纳率: 0%
浏览 866

如何在 JavaScript 中复制到剪贴板?

What is the best way to copy text to the clipboard? (multi-browser)

I have tried:

function copyToClipboard(text) {
    if (window.clipboardData) { // Internet Explorer
        window.clipboardData.setData("Text", text);
    } else {  
        unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
        const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);  
        clipboardHelper.copyString(text);
    }
}

but in Internet Explorer it gives a syntax error. In Firefox, it says unsafeWindow is not defined.

A nice trick without flash: How does Trello access the user's clipboard?

转载于:https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript

  • 写回答

30条回答 默认 最新

  • YaoRaoLov 2008-12-30 13:33
    关注

    Reading and modifying the clipboard from a webpage raises security and privacy concerns. However, in Internet Explorer, it is possible to do it. I found this example snippet:

        <script type="text/javascript">
            function select_all(obj) {
                var text_val=eval(obj);
                text_val.focus();
                text_val.select();
                r = text_val.createTextRange();
                if (!r.execCommand) return; // feature detection
                r.execCommand('copy');
            }
        </script>
        <input value="http://www.sajithmr.com"
         onclick="select_all(this)" name="url" type="text" />

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?