navigator.clipboard未定义

drm*_*wer 10 clipboard google-chrome

为什么navigator.clipboard总是undefined在以下代码段中?

var clipboard = navigator.clipboard;
if (clipboard == undefined) {
    console.log('clipboard is undefined');
} else {
    clipboard.writeText('stuff to write').then(function() {
        console.log('Copied to clipboard successfully!');
    }, function() {
        console.error('Unable to write to clipboard. :-(');
    });
}
Run Code Online (Sandbox Code Playgroud)

有关剪贴板API的更多信息,请访问此处.

Chrome版本:68.0.3440.106.

我确信这在某些方面有效,但不再是.这很令人困惑,因为这个表表明Clipboard API是在Chrome中实现的(已经有一段时间了),但是这个特定的API方法表明API的所有方法都不受支持?

Sim*_*aut 22

您可以编写一个多合一的包装函数。

  • 如果在安全上下文 (https) 中:使用导航器剪贴板 api
  • 如果不是:使用“视口外隐藏文本区域”技巧
// return a promise
function copyToClipboard(textToCopy) {
    // navigator clipboard api needs a secure context (https)
    if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard api method'
        return navigator.clipboard.writeText(textToCopy);
    } else {
        // text area method
        let textArea = document.createElement("textarea");
        textArea.value = textToCopy;
        // make the textarea out of viewport
        textArea.style.position = "fixed";
        textArea.style.left = "-999999px";
        textArea.style.top = "-999999px";
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        return new Promise((res, rej) => {
            // here the magic happens
            document.execCommand('copy') ? res() : rej();
            textArea.remove();
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

用 :

copyToClipboard("I'm going to the clipboard !")
    .then(() => console.log('text copied !'))
    .catch(() => console.log('error'));
Run Code Online (Sandbox Code Playgroud)

ps:不要在像jsfiddle/copeden/...这样的repl中尝试

  • 自 document.exeCommand 已被弃用以来的任何其他方式 (7认同)
  • 酷,简洁一点:`textArea.style.position = "absolute"; textArea.style.opacity = 0;`并且我认为焦点调用是不必要的 (2认同)

Jos*_*Lee 19

这需要一个安全的来源 - HTTPS或localhost(或通过运行带有标志的Chrome来禁用).与ServiceWorker一样,此状态由导航器对象上是否存在属性指示.

https://developers.google.com/web/updates/2018/03/clipboardapi

这在界面中[SecureContext]的规范中有说明:https://w3c.github.io/clipboard-apis/#dom-navigator-clipboard

您可以检查状态window.isSecureContext以了解功能是否不可用.安全的背景| MDN

是的,您应该设置HSTS以确保HTTP重定向到HTTPS.

  • 在“chrome://flags”中,启用“将不安全的来源视为安全”并为其提供所需的来源。 (6认同)
  • 顺便说一句,暂时禁用 https 检查的标志是例如。--unsafely-treat-insecure-origin-as-secure=http://www.myexamplesite.com。 (3认同)

Jul*_*sta 9

尝试这个:

if (typeof (navigator.clipboard) == 'undefined') {
    console.log('navigator.clipboard');
    var textArea = document.createElement("textarea");
    textArea.value = linkToGo;
    textArea.style.position = "fixed";  //avoid scrolling to bottom
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        toastr.info(msg);
    } catch (err) {
        toastr.warning('Was not possible to copy te text: ', err);
    }

    document.body.removeChild(textArea)
    return;
}
navigator.clipboard.writeText(linkToGo).then(function () {
    toastr.info(`successful!`);
}, function (err) {
    toastr.warning('unsuccessful!', err);
});
Run Code Online (Sandbox Code Playgroud)


Lau*_*det 6

当 HTTPS 尚不可用并且 document.execCommand('copy') 的解决方案不起作用时,用于复制工具提示的最小解决方案。但它要求用户手动选择并复制警报中显示的内容。

function copyToClipboard(text) {
    if(navigator.clipboard) {
        navigator.clipboard.writeText(text);
    }
    else{
        alert(text);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

在 localhost 中,剪贴板被 Chrome 浏览器阻止。您可以通过转到以下路径来检查这一点

Chrome > 设置 > 隐私和安全 > 站点设置 > 查看跨站点存储的权限和数据,然后单击将在页面上提及的本地主机 URL,并检查剪贴板的权限