chrome中不允许execCommand onMouseUp

时间:2019-03-05 09:57:19

标签: javascript

我正在尝试在用户释放鼠标时自动复制所选内容。但是,似乎onMouseUp未被识别为用户操作,并且当前不允许执行execCommand。 (execCommand返回false)。

这将起作用: 鼠标向下>拖动>鼠标向上,都在一秒钟内完成 (因为我认为onMouseDown是有效的用户操作)

这将不起作用: 鼠标向下>拖动一会儿>鼠标向上

这是演示代码:

<html>
    <head>
        <script>
            function mouseUp() {
                console.log(document.execCommand('copy'));
            }
        </script>
    </head>
    <body onmouseup="mouseUp()">
        <p>some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text <p>
    </body>
</html>

有什么主意吗?

1 个答案:

答案 0 :(得分:0)

https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand#Browser_compatibility所述,复制功能已弃用(我找不到适用于Chrome的任何功能。)。

我用navigator.clipboard.writeText()实现了相同的功能。

<html>
    <head>
        <script>
            function mouseUp() {
                navigator.clipboard.writeText(window.getSelection()).then(function() 
                {
                    console.log("set");
                }, function() {
                     console.log("failed");
                });
            }
        </script>
    </head>
    <body onmouseup="mouseUp()">
        <p>some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text <p>
    </body>
</html>

您可能需要先获得https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard#Using_the_Clipboard_API上所述的权限

  

对于页面脚本,需要Permissions API的“剪贴板写入”权限。您可以使用navigator.permissions.query()

检查该权限。