web API -Clipboard Async API 剪切板 复制 粘贴

剪切板是一些操作系统提供的一个缓冲区,用于短期存储,以及应用程序内部和应用程序之间的数据传输。
使用剪切板主要可以执行三种操作,copy cut paste。


复制内容到剪切板是开放的,不需要用户许可。但是粘贴到用户应用程序则需要授权, Permission API

注意:通过包含 Clipboard Async API,就可以不用document.execCommad()函数了

demo:

<!DOCTYPE html>
<html>
    <head>
        <title>demo</title>
        <style type='text/css'>
        body{
            height: 1000px;
            margin: 0;
            padding: 0;
        }
        .hidden{
            overflow: hidden;
        }
        .show{
            display: block;
        }
        .btn{
            color: #fff;
            background-color: red;
            width: 100px;
            margin-bottom: 50px;
            line-height: 30px;
            text-align: center;
        }
        
        </style>
    </head>
    <body>
        <input id='inputInfo'/>
       <div class='btn' onclick="copy()">copy</div>
       <div class='btn' onclick="performPaste()">paste</div>
       <p id='pasteInfo'></p>
    </body>
</html>
<script>
function copy(){
    if(canUseClipboard()){
         const text=document.getElementById('inputInfo').value;
        performCopy(text);
    }
}
 function paste(text){
    document.getElementById('pasteInfo').innerText=text;
 }
 async function performPaste(){
     try{
        const text=await navigator.clipboard.readText();
         console.log('paste success');
         paste(text);
     }catch(error){
        console.log('paste error'+error)
     }
 }
async function performCopy(text){
    event.preventDefault();
    try{
        await navigator.clipboard.writeText(text);
         console.log('copy success');
    }catch(err){
        console.log('copy error');
    }
    
}
function canUseClipboard(){
    if(navigator.clipboard&&navigator.clipboard.read&&navigator.clipboard.write)
    return true;
    return false;
}
</script>

 

posted on 2021-02-01 10:53  半夏微澜ぺ  阅读(210)  评论(0)    收藏  举报