有没有办法打开 mailto: 和 tel: 来自 service worker 的链接?

Is there a way to open mailto: and tel: links from a service worker?

我正在使用由 Service Worker 处理的推送通知。

使用通知的主要动机是提供“呼叫”或“邮寄至”等操作,我认为该行为与单击“mailto:”相同link。

它在 windows 上使用 chrome 可以正常工作(例如,在单击时启动邮件应用程序)但在 android 上使用 chrome 失败,导致出现黑色标签url "mailto:..." 写在上面。

// Service Worker
self.addEventListener('notificationclick', function(event) {
  const { contactRequest } = JSON.parse(event.notification.data);
  switch(event.action) {
    case 'call':
      return clients.openWindow('tel:' + contactRequest.phone);
    case 'mail':
      return clients.openWindow('mailto:' + contactRequest.email);
  }
});

更新了更多信息

这似乎是一个以多种方式表现出来的错误 - 声称已在此处修复,原因不相关 - https://bugs.chromium.org/p/chromium/issues/detail?id=792990

通知功能本身没有太多选项,您只能使用 openWindow 创建或使用 window 来执行其他选项。

Chrome 中面临的问题也在 MDN 中得到承认 - https://developer.mozilla.org/en-US/docs/Web/API/Clients/openWindow

这里有两种方法

  1. 打开或聚焦您的应用程序并添加 hash 哪些服务器作为通知被点击的标记 - 这让您可以添加目标 _top_blank

伪代码归功于MDN

// Notification click event listener
self.addEventListener('notificationclick', e => {
  // Close the notification popout
  e.notification.close();
  // Get all the Window clients
  e.waitUntil(clients.matchAll({ type: 'window' }).then(clientsArr => {
    // If a Window tab matching the targeted URL already exists, add a "#mailNotification"
    const hadWindowToFocus = clientsArr.some(windowClient => windowClient.url === e.notification.data.url ? (windowClient.navigate(e.notification.data.url+"#mailNotification").then(function(client){client.focus()}), true) : false);

// Add additional code to add a 
    // Otherwise, open a new tab to the applicable URL and focus it.
    if (!hadWindowToFocus) clients.openWindow(e.notification.data.url+"#mailNotification").then(windowClient => windowClient ? 
    windowClient.navigate(e.notification.data.url+"#mailNotification").then(function(client){client.focus()})
     : null);
  }));

// Then in your page, you can just use window.onhashChange event
window.onhashchange = weFixChromeLinks



function weFixChromeLinks () {

// ... Create an anchor tag that is formatted to your mailto has a target _top or _blank, hide the link and dispatch a click.
}
  1. 较早的方法

由于 clients.openWindow 方法不提供针对 _top window 的能力,您可能必须设置支持 _top 的中间页面 - 即

// Your intermediate page 
window.open('mailto...','_top')

结束语 问题本身是 丑陋的 - 浏览器应该知道意图,例如:应用程序,邮件程序等 - 似乎 Chrome for android 对待它就像另一个URL 惨遭失败。