navigator.clipboard未定义 [英] navigator.clipboard is undefined

查看:875
本文介绍了navigator.clipboard未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why is navigator.clipboard always undefined in the following snippet?

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. :-(');
    });
}

有关剪贴板API的更多信息,请参见此处

More on the clipboard API can be found here.

Chrome版本:68.0.3440.106。

Chrome Version: 68.0.3440.106.

我确定这在某些时候可以使用,但现在不再可用。这令人困惑,因为此表建议剪贴板API已在Chrome中实现(已经存在了一段时间),但此表中的特定API方法表明不支持该API的任何方法?

I'm sure this was working at some point, but no longer is. It's confusing because this table suggests that the Clipboard API is implemented in Chrome (has been for some time), but this table of specific API methods suggests that none of the methods of the API is supported??

推荐答案

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

This requires a secure origin — either HTTPS or localhost (or disabled by running Chrome with a flag). Just like for ServiceWorker, this state is indicated by the presence or absence of the property on the navigator object.

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

这在接口上带有[SecureContext]的规范中指出: https://w3c.github.io/clipboard-apis/#dom-navigator-clipboard

This is noted in the spec with [SecureContext] on the interface: https://w3c.github.io/clipboard-apis/#dom-navigator-clipboard

您可以检查<$ c的状态$ c> window.isSecureContext 来了解是否是功能不可用的原因。 保护上下文| MDN

You can check the state of window.isSecureContext to learn if that's the reason a feature is unavailable. Secure contexts | MDN

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

And yes, you should set up HSTS to make sure HTTP redirects to HTTPS.

这篇关于navigator.clipboard未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆