如何将 Web 通知内容复制到剪贴板



我正在使用 Firebase 云消息传递 (FCM( 发送数据消息,以便可以使用 Service Worker 处理通知。现在,我使用 Service Worker 显示通知,当我单击通知时,我想在剪贴板中复制通知的内容。

const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler((payload)=> {
const title = payload.data.title;
const options = {
body: payload.data.body
};
return self.registration.showNotification(title,
options);
});
self.addEventListener('notificationclick', (event)=>{
console.log(event);
navigator.clipboard.writeText(event).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
});

单击通知时notificationclick将触发事件。但我navigator.clipboard是不确定的。我也在我的网站上使用安全域名。我也无法使用document.execcommand('copy')因为无法使用服务工作者访问 DOM。您能否建议一种无需打开任何 URL 即可复制通知内容的方法?

不能从 ServiceWorker 复制到剪贴板。您需要一个活动的前台浏览器选项卡/窗口才能复制到剪贴板。

来自 chrome 网站更新存档 https://developers.google.com/web/updates/2018/03/clipboardapi

与许多新 API 一样,navigator.clipboard 仅支持通过 HTTPS 提供的页面。为了帮助防止滥用,仅当页面是活动选项卡时,才允许访问剪贴板。活动选项卡中的页面无需请求权限即可写入剪贴板,但从剪贴板读取始终需要权限。

我还检查了 ServiceWorker 和剪贴板 API 的浏览器规格,但没有一个定义任何关于服务工作者上下文的具体内容。

编辑:我已经 ping 了该帖子的作者关于这个特定问题 https://mobile.twitter.com/_developit/status/1264290519926128641

我不相信它在服务工作者中可用。我的建议是让通知单击处理程序打开一个页面(如果尚未打开(,并在收到事件时在该页面中同步调用 writeText((。

您可以使用客户端发布消息 API:

服务工作者 :

self.addEventListener('notificationclick', (event)=>{
console.log(event);
if (!event.clientId) return;
const client = await clients.get(event.clientId);
if (!client) return;
client.postMessage({
type: 'clipboard',
msg: event
});
});

简单脚本:

navigator.serviceWorker.addEventListener('message', event => {
if(event.data.type === 'clipboard') {
navigator.clipboard.writeText(event.data.msg).then(function() {
console.log('Async: Copying to clipboard was successful!');
}, function(err) {
console.error('Async: Could not copy text: ', err);
});
}
});

请记住,Safari 不支持此功能。

最新更新