我正在使用 Firebase Cloud Messaging (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')
因为使用 Service Worker 无法访问 DOM。您能否建议一种无需打开任何网址即可复制通知内容的方法?
最佳答案
您不能从 ServiceWorker 复制到剪贴板。您需要一个事件的前台浏览器选项卡/窗 Eloquent 能复制到剪贴板。
来自 chrome 网页更新存档 https://developers.google.com/web/updates/2018/03/clipboardapi
As with many new APIs, navigator.clipboard is only supported for pages served over HTTPS. To help prevent abuse, clipboard access is only allowed when a page is the active tab. Pages in active tabs can write to the clipboard without requesting permission, but reading from the clipboard always requires permission.
我还检查了 ServiceWorkers 和剪贴板 API 的浏览器规范,没有一个定义任何关于服务 worker 上下文的特定内容。
编辑:我已经就这个特定问题联系了该帖子的作者 https://mobile.twitter.com/_developit/status/1264290519926128641
I don't believe it's available in service worker. My suggestion would be to have the notification click handler open a page if not already open, and call writeText() synchronously within that page when it received the event.
关于javascript - 如何将网络通知内容复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61862872/