js实现复制粘贴

在一些页面里,有时候会需要用户点击按钮或者控件需要把一些文字内容写入用户设备的剪切板里。在js中如何通过代码实现?接下来是两种实现方法!

使用document.execCommand API

注意 document.execCommand API 是同步执行,如果数据量大 可能会阻塞页面加载,这种办法能兼容老版本浏览器和大部分浏览器。

/**
 * 将文字写入剪切板 
 * @param {string} text
 * @returns {boolean} 返回执行结果
 */
function exeCommandCopyText(text) {
    try {
        const t = document.createElement('textarea')
        t.nodeValue = text
        t.value = text
        document.body.appendChild(t)
        t.select()
        document.execCommand('copy');
        document.body.removeChild(t)
        return true
    } catch (e) {
        console.log(e)
        return false
    }
}
  • vue中使用
<template>
    <div>
        <button @click="cpoy">点击复制文字内容</button>
    </div>
</template>

<script>
    function exeCommandCopyText(text) {
        try {
            const t = document.createElement('textarea')
            t.nodeValue = text
            t.value = text
            document.body.appendChild(t)
            t.select()
            document.execCommand('copy');
            document.body.removeChild(t)
            return true
        } catch (e) {
            console.log(e)
            return false
        }
    }
    export default {
        methods: {
            cpoy() {
                let content = `123
            456
            789` // 包含了换行符
                let flag = exeCommandCopyText(content)
                console.log(flag ? "复制成功" : "复制失败")
            }
        }
    }
</script>

使用navigator.clipboard API

使用前需注意:在安全的网站中可以通过访问 navigator.clipboard 。这里的安全网站是指:https协议的网站或者 本地localhost ,不然访问 navigator.clipboard 会返回undefined。此API比较新,在现代主流浏览器支持(最早2018年)。

/**
 * 将文字写入剪切板 
 * @param {string} text
 * @returns {Promise} 返回promise对象
 */
function clipboardCopyText(text) {
    // 在调用前 先访问是否存在 clipboard 对象
    if (navigator.clipboard) {
        return navigator.clipboard.writeText(text)
    }
    return Promise.reject("无法访问 navigator.clipboard 对象")
}

let str = `
你快乐吗?
我很快乐!
`
clipboardCopyText(str).then(() => {
    console.log("复制成功到剪切板");
}).catch(err => {
    console.log("复制失败了");
})

结合使用

因为 document.execCommand 将要废弃,所以在新版本浏览器可能会无法正常使用。 MDN 推荐使用navigator.clipboard。所以可以组合新老API,去支持大部分的新旧浏览器。

/**
 * 将文字写入剪切板 
 * @param {string} text
 * @returns {Promise} 返回promise对象
 */
function copyText(text) {
    // 在调用前 先访问是否存在 clipboard 对象
    if (navigator.clipboard) {
        return navigator.clipboard.writeText(text)
    } else {
        // 不存在使用 老版本API execCommand
        try {
            const t = document.createElement('textarea')
            t.nodeValue = text
            t.value = text
            document.body.appendChild(t)
            t.select()
            document.execCommand('copy');
            document.body.removeChild(t)
            return Promise.resolve()
        } catch (e) {
            console.log(e)
            return Promise.reject(e)
        }
    }
}

copyText("今天晚上吃什么?").then(() => {
    console.log("复制成功!");
}).catch(() => {
    console.log("复制失败");
})
posted @ 2023-06-12 17:55  阿政想暴富  阅读(2672)  评论(0编辑  收藏  举报