当前位置: 首页 > 知识库问答 >
问题:

为什么serviceworker会导致每一秒jquery帖子都立即停止?

邴宏大
2023-03-14

我在标题中所述的内容仅在chrome浏览器中出现,如在firefox中“(“navigator”中的“serviceWorker”)总是错误的,“console.warn('此浏览器不支持服务工作者');”而是触发。

如果你清除浏览器或隐姓埋名运行,那么它最初是工作的,但是当你第一次注销,然后重新登录时,问题就开始了。

这就是网络日志里的样子

以下是我注册软件的代码:

function activateSW(){
    if('serviceWorker' in navigator){
        if(window.location.pathname != '/'){
            //register with API
            if(!navigator.serviceWorker.controller) navigator.serviceWorker.register('/service-worker', { scope: '/' });
            //once registration is complete
            navigator.serviceWorker.ready.then(function(serviceWorkerRegistration){
                //get subscription
                serviceWorkerRegistration.pushManager.getSubscription().then(function(subscription){
                    //enable the user to alter the subscription
                    $('.js-enable-sub-test').removeAttr("disabled");
                    //set it to allready subscribed if it is so
                    if(subscription){
                        $('.js-enable-sub-test').prop("checked", true);
                        $('.js-enable-sub-test').parent().addClass('checked');
                    }
                });
            });
        }   
    }else{  
        console.warn('Service workers aren\'t supported in this browser.');  
    } 
}

'/service-Worker'是发送到index.php的请求(通过. htaccess)。它最终以这个函数结束:

function serviceworkerJS($params){

    $hash = API::request('settings', 'getSWHash', '');

    if($hash != false){
        setcookie('SW_Hash', $hash, time() + (86400 * 365 * 10), "/");

        header('Content-type: text/javascript');

        echo "'use strict';
var hash = '".$hash."';";

        include(ROOT_PATH.'public/js/service-worker.js');
    }elseif(isset($_COOKIE['SW_Hash'])){
        header('Content-type: text/javascript');

        echo "'use strict';
var hash = '".$_COOKIE['SW_Hash']."';";

        include(ROOT_PATH.'public/js/service-worker.js');
    }else{
        header('HTTP/1.1 404 Not Found');
    }

}

服务人员。如中所示的jschrome://serviceworker-internals/看起来是这样的:(对地址的几处引用已被星号替换)

'use strict';
var hash = 'bd8e78963deebf350f851fbf8cdc5080';
var *****_API_ENDPOINT = 'https://*********.***/';

//For displaying notifications
function showNotification(title, body, icon, data, id) {
    var notificationOptions = {
        body: body,
        icon: icon,
        tag: id,
        data: data
    };
    //possibly unnecessary
    if(self.registration.showNotification){
        return self.registration.showNotification(title, notificationOptions);
    }else{
        return new Notification(title, notificationOptions);
    }
}

//asks the server for messages and sends them for displaying.
function getMessages(event){
    //showNotification('debug', 'initial', '', '', 'debug1');

    //build question
    var FD = new FormData();
    FD.append('hash', hash);

    //ask start20 for the notifications
    event.waitUntil(
        fetch(*****_API_ENDPOINT + 'ajax-get-SW-notification/', {method: 'post', body: FD}).then(function(response){

            //something went wrong
            if (response.status !== 200){
                console.log('Error communicating with ******, code: ' + response.status);
                showNotification('debug', 'picnic', '', '', 'debug2');
                throw new Error();
            }

            //decode the response
            return response.json().then(function(data){

                var len = data.notifications.length;
//showNotification('debug', len, '', '', 'propertyName');
                //Display
                for(var i = 0; i < len -1; i++){
                    showNotification(data.notifications[i].title, 
                                    data.notifications[i].body, 
                                    data.notifications[i].imageurl, 
                                    data.notifications[i].linkurl,
                                    data.notifications[i].hash);
                }

                //the last one needs to be returned to complete the promise
                return showNotification(data.notifications[len -1].title, 
                                        data.notifications[len -1].body, 
                                        data.notifications[len -1].imageurl, 
                                        data.notifications[len -1].linkurl,
                                        data.notifications[len -1].hash);
            });
        })
    );
}

//when the user installs a new SW
/*self.addEventListener('activate', function(event){
    //getMessages(event);
    //event.preventDefault();
    event.waitUntil(return self.registration.showNotification('bicnic', { body: '*p' }));
});*/

//when the serviceworker gets a puch from the server
self.addEventListener('push', function(event){
    getMessages(event);
    event.preventDefault();
});

//get the link associated witht he message when a user clicks on it
self.addEventListener('notificationclick', function(event){

    //ask if the notification has any link associated with it
    var FD = new FormData();
    FD.append('hash', event.notification.tag);

    //get the link
    event.waitUntil(
        fetch(******_API_ENDPOINT + 'ajax-notification-has-link/', {method: 'post', body: FD}).then(function(response){

            //something went wrong
            if (response.status !== 200){
                console.log('Error communicating with ********, code: ' + response.status);
                return;
            }

            //decode the response
            return response.json().then(function(data){

                //if there's a link associated with the message hash
                if(data.link){
                    console.log(******_API_ENDPOINT + 'notification-link/' + event.notification.tag);
                    return clients.openWindow(*****_API_ENDPOINT + 'notification-link/' + event.notification.tag);
                }

            });
        })
    );

});


//unnecessary?
/*self.addEventListener('install', function(event){
    //event.preventDefault();
});

self.addEventListener("fetch", function(event) {

});//*/

现在,如果您注释掉“if(!navigator.serviceWorker.controller)navigator.serviceWorker.register('/service worker',{scope:'/'})”然后,问题消失,但ofc服务人员订阅和取消订阅停止工作。(if语句似乎没有什么作用,只是为了解决这个问题而添加的)

我已经尝试过许多版本的activateSW(),在不同的条件下运行不同的表达式,但还没有成功制作出一个不破坏serviceworker的版本。我也尝试捕捉不同点(注册、帖子)上的错误,但没有成功,因为它们都没有抛出任何错误。

我怀疑的问题可能是,当您注册serviceWorker时,会触发一个激活事件。现在,如果您发现了这一点并完成了事件promise,那么您将无法订阅。但是,我怀疑serviceWorker在您注销时仍然处于活动状态,这会导致问题。

如果你有问题或想看到更多的代码,然后只是问。

编辑以下是html" target="_blank">解决方案:

self.addEventListener("fetch", function(event) {
    event.respondWith(
        fetch(event.request)
    );
});

共有1个答案

单于浩邈
2023-03-14

您看到的是ChromeDevTools的网络面板中令人困惑的噪音,但不应该对应用程序的行为产生实际影响。

如果服务工作人员控制页面,但不包括提取事件处理程序,则当前版本的Chrome(M44稳定和M46金丝雀)最终会以(已取消)状态记录网络面板中的所有网络请求,就像你看到的。实际的请求仍然在没有服务工作人员干预的情况下发出,这是第二个成功登录的条目。从您的页面的角度来看,事情应该如预期的那样工作,但我完全理解这种混乱。

我听说有计划让Chrome的service worker实现在发出网络请求且没有fetch事件处理程序时表现得更像“无操作”。我不知道这些计划进展得有多远,但我预计一旦发生这种情况,你所看到的噪音就会消失。

 类似资料:
  • 我在Ubuntu 14.04上安装了redis,而且我似乎几乎每周都有完成RDB快照的问题。Redis版本是3.0.4 64位。 3838:M 24 Feb 09:46:28.826*后台保存成功终止 3838:M 24 Feb 09:47:29.088*在60秒内更改100000次。拯救 3838:M 24 Feb 09:47:29.230*后台保存由pid 17281启动 17281:信号处理

  • 问题内容: 我在后台运行一个容器 它迅速退出。但是,如果我在前台运行,则可以正常运行。我使用检查了日志 没有错误。有任何想法吗? DOCKERFILE start-all.sh 问题答案: 一个Docker容器的主要过程完成后退出。 在这种情况下,它将在脚本结束时退出。我对hadoop不太了解,无法在这种情况下告诉您如何做,但是您需要要么在前台运行某些东西,要么使用诸如runit或supervis

  • 问题内容: 好吧,我试图理解并阅读可能导致它的原因,但我却无法理解: 我的代码中有这个地方: 事实是,当它尝试调用某些方法时,它将引发而不是其他预期的异常(特别是)抛出 。我实际上知道调用了什么方法,所以我直接转到该方法代码,并为应该抛出的行添加了一个块 ,它实际上按预期抛出。然而,当它上升时,以某种方式更改了上面的代码并没有 按预期进行。 是什么原因导致这种行为的?我该如何检查? 问题答案: 通

  • 为什么我在下面的代码段中的X轴上有一个溢出? 在我的网格容器上应用时,就会产生溢出。 null null https://codepen.io/anon/pen/wdjexz?editors=1100

  • uniapp 为什么每次进来都会执行onLoad钩子? 症状:不管是第一次还是第N次进去都会执行onload,印象中应该只有第一次进来才会执行一次吧,有谁遇到过吗,难道是用redirectTo跳转才会这样吗

  • 问题内容: 即使模型类中没有验证约束,我也会收到此错误(所有成员变量均已正确设置,但我在创建对象时仍然遇到此异常)。如何调试此错误? 问题答案: 每个都有一个数组。每个显示了您要保留的bean的哪个属性被侵犯。正如@Arthur正确指出的那样,违反Java持久性注释的结果也以s 结尾。 要调试你的问题,我会暂时赶在并打印出每个如下: