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

How to copy web notification content to clipboard

我正在使用 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'),因为无法使用 Service Worker 访问 DOM。能否请您建议一种无需打开任何内容即可复制通知内容的方法url?

您可以使用客户端 postMessage 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 不支持此功能。

您不能从 ServiceWorker 复制到剪贴板。您需要一个活动的前台浏览器 tab/window 才能复制到剪贴板。

来自 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 和 Clipboard API 的浏览器规范,none 定义了关于服务工作者上下文的任何特定内容。

编辑:我已经就这个特定问题 https://mobile.twitter.com/_developit/status/1264290519926128641

联系了 post 的作者

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.