How to bring chrome to foreground from a web app

守給你的承諾、 提交于 2019-12-02 13:08:23

I solved it by adding this in the service worker file:

   self.addEventListener('push', function (e) {
        if (e.data) {
            var payloadData = e.data.json();
            self.clients.matchAll({includeUncontrolled: true}).then(function (clients) {
                clients[0].postMessage(payloadData); // you can do foreach but I only needed one client to open one window
            });
        }
    });

And this in the main.js file:

function openNotificationWindow(url) {
    var myWindow = window.open(url);   // Opens a new window
    myWindow.focus();
    myWindow.location.reload(true);
}

navigator.serviceWorker.addEventListener('message', function (event) {
    if (typeof event.data.data !== 'undefined') {
        openNotificationWindow(url);
    }
});

Now everytime I send a notification either with the window in foreground or in the background the push event fires in the serviceworker and then is using postMessage() to comunicate with the some main.js file where you have access to the window DOM component.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!