Javascript 服务工作者:当用户单击通知时,将其重定向到不同的url
此代码段有助于将应用程序选项卡置于焦点位置,或使用该URL打开一个新选项卡。如果选项卡已打开,是否有方法更改URL(基于用户单击的通知)Javascript 服务工作者:当用户单击通知时,将其重定向到不同的url,javascript,service-worker,web-push,Javascript,Service Worker,Web Push,此代码段有助于将应用程序选项卡置于焦点位置,或使用该URL打开一个新选项卡。如果选项卡已打开,是否有方法更改URL(基于用户单击的通知) event.waitill( 客户。匹配球({ 键入:“窗口” }) .then(函数(WindowClient){ 对于(var i=0;i
event.waitill(
客户。匹配球({
键入:“窗口”
})
.then(函数(WindowClient){
对于(var i=0;i
这个方法听起来像你想要的。您应该能够执行以下操作:
// Assume that you want to find the first window that is currently open
// to originalUrl, and navigate that window to navigationUrl.
// If there is no window currently at originalUrl, then open a new window.
event.waitUntil(
clients.matchAll({type: 'window'})
.then(clients => clients.filter(client => client.url === originalUrl))
.then(matchingClients => {
if (matchingClients[0]) {
return matchingClients[0].navigate(navigationUrl)
.then(client => client.focus());
}
return clients.openWindow(navigationUrl);
})
);
我建议采用一种不同的体系结构,通过这种体系结构,您可以向客户发送消息,然后客户可以决定在您需要的任何情况下应该做什么。注意,如果它需要聚焦,
client.postMessage('focus')
。如果需要打开一个新窗口,client.postMessage('window',url)
。如果需要重定向,client.postMessage('redirect',url)
同意!这就是我现在正在做的,但我想知道,既然我已经有了标签,是否可以从这里开始呢。
// Assume that you want to find the first window that is currently open
// to originalUrl, and navigate that window to navigationUrl.
// If there is no window currently at originalUrl, then open a new window.
event.waitUntil(
clients.matchAll({type: 'window'})
.then(clients => clients.filter(client => client.url === originalUrl))
.then(matchingClients => {
if (matchingClients[0]) {
return matchingClients[0].navigate(navigationUrl)
.then(client => client.focus());
}
return clients.openWindow(navigationUrl);
})
);