The Clipboard API has been blocked because of a permissions policy applied to the current document

原创
前端路迹
2022-11-23 15:52
编辑于 2022-11-23 16:04

使用 navigator.clipboard.writeText 将文本写入系统的剪贴板,正常情况下没有问题,但是如果是iframe内调用,会报错提示。

DOMException: The Clipboard API has been blocked because of a permissions policy applied to the current document. See https://goo.gl/EuHzyv for more details.

这时候需要在 iframe上加上allow属性。

<iframe src="index.html" allow="clipboard-read; clipboard-write"></iframe>

如果遇到无法调整iframe的属性的情况下,可以在失败的时候再调用 document.execCommand 来复制文本。代码如下。

function fallbackCopyTextToClipboard(text) {
    var textArea = document.createElement('textarea')
    textArea.value = text

    textArea.style.top = '0'
    textArea.style.left = '0'
    textArea.style.position = 'fixed'

    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()

    try {
        document.execCommand('copy')
    } catch (err) {}

    document.body.removeChild(textArea)
}
function copyTextToClipboard(text) {
    if (!navigator.clipboard) {
        fallbackCopyTextToClipboard(text)
        return
    }
    navigator.clipboard.writeText(text).then(
        function () {},
        function (err) {
            fallbackCopyTextToClipboard(text)
        }
    )
}

export default copyTextToClipboard
转载请注明出处。本文地址: https://www.qinshenxue.com/article/clipboard-api-has-been-blocked-because-of-a-permissions-policy-applied-to-the-current-document.html
关注我的公众号