20

我有两个子域:https://abc.xxxx.comhttps://xyz.xxxx.com。所以我的问题:

1)。是否可以 从https://abc.xxxx.com为https://xyz.xxxx.com注册服务人员 ?如果是,那怎么办?

2)。如果http://abc.xxxx.com ( http不安全) 那么无论如何都要从http://abc.xxxx.com为https://xyz.xxxx.com注册一个服务工作者,比如在 iframe 或其他东西中......

这是一个真实的情况,我面临着我的多个子域。任何帮助表示赞赏。提前致谢。

4

4 回答 4

23

以下是一些我认为应该解决您在问题中提出的各个要点的一般性答案:

  • 每个注册的服务工作者都有一个关联的scope,它指示服务工作者可以控制的网页集。Service Worker的scope是一个 URL,该 URL 必须与注册 Service Worker 的页面具有相同的来源,并且必须是与页面对应的路径级别相同的 URL,或者是一个或多个级别的路径下。默认值scope对应于与 service worker 脚本位置相同的路径级别。由于这个限制,不可能navigator.serviceWorker.register(...)从一个(子)域上的页面调用并最终得到一个控制另一个(子)域上的页面的服务工作者。

  • 有一些限制可以防止您https: <iframe>http:页面上抛出并使用它来注册服务工作者。在 https iframe 中注册服务工作者时请参阅DOMException

  • 虽然我不知道它与您的问题直接相关,但在您的服务工作者代码中明确调用fetch()资源http:将导致当前版本的 Chrome 失败,因为fetch()在服务工作者中不允许使用混合内容。我不知道这方面的事情是否 100% 解决了,而且这个开放的错误仍然是相关的。

如果您的页面同时存在于两者上abc.123.comxyz.123.com并且您希望这两组页面都由服务工作者控制,那么您需要有两个单独的服务工作者注册。每个注册都需要为您的服务工作者 JS 文件的副本,该文件托管在与顶级页面对应的相应域上,并且所有页面和服务工作者脚本都需要通过https:.

话虽如此,您可以通过在页面上包含跨域来启动不同域的服务工作者注册<iframe>,但主机页面和<iframe>需要通过https:. 正常的服务工作人员范围限制适用,因此,例如,如果您想为将覆盖整个https://other-domain.com/范围的其他域注册服务工作人员,您需要确保正在注册的服务工作人员脚本的位置位于顶级,例如https://other-domain.com/service-worker.js,不在https://other-domain.com/path/to/service-worker.js。这是例如AMP 项目通过 <amp-install-serviceworker>element使用的方法。

于 2015-08-07T17:11:13.393 回答
5

Service Worker scripts must be hosted at the same origin (Protocol + Domain name + Port).每个子域都被认为是不同的来源,因此,您需要为每个子域注册一个服务工作者。这些工人中的每一个都有自己的cachescope

于 2016-10-07T05:17:38.270 回答
0

尝试使用 Ngnix proxy_pass。这对我有用。

于 2018-12-29T10:06:10.963 回答
-1

我的不好,我误解了一点。好吧,这是代码

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
                //jquery selector for enabling whatever you use to subscribe.removeAttr("disabled");
                //set it to allready subscribed if it is so
                if(subscription){
                    //code for showing the user that they're allready subscribed
                }
            });
        });
    }   
}else{  
    console.warn('Service workers aren\'t supported in this browser.');  
}

然后这是您订阅/取消订阅的事件

// subscribe or unsubscribe to the ServiceWorker
$(document.body).on('change', /*selector*/, function(){
    //new state is checked so we subscribe
    if($(this).prop('checked')){
        navigator.serviceWorker.ready.then(function(serviceWorkerRegistration){
            serviceWorkerRegistration.pushManager.subscribe()  
                .then(function(subscription){  
                    // The subscription was successful  
                    console.log('subscription successful'); //subscription.subscriptionId

                    //save in DB - this is important because 
                    $.post($('#basePath').val() + 'settings/ajax-SW-sub/', {id:subscription.subscriptionId}, function(data){
                        //console.log(data);
                    }, 'json');

                    }).catch(function(e) {  
                        if (Notification.permission === 'denied') {  
                            // The user denied the notification permission which  
                            // means we failed to subscribe and the user will need  
                            // to manually change the notification permission to  
                            // subscribe to push messages
                            console.warn('Permission for Notifications was denied');
                        } else {  
                            // A problem occurred with the subscription; common reasons  
                            // include network errors, and lacking gcm_sender_id and/or  
                            // gcm_user_visible_only in the manifest.  
                            console.error('Unable to subscribe to push.', e);
                        }  
                    });  
        });//*/
    //new state us unchecked so we unsubscribe
    }else{
        $('.js-enable-sub-test').parent().removeClass('checked');
        //get subscription
        navigator.serviceWorker.ready.then(function(reg) {
            reg.pushManager.getSubscription().then(function(subscription) {
                //unregister in db
                $.post($('#basePath').val() + 'settings/ajax-SW-unsub/', {id:subscription.subscriptionId}, function(data){
                    //console.log(data);
                }, 'json');

                //remove subscription from google servers
                subscription.unsubscribe().then(function(successful) {
                    // You've successfully unsubscribed
                    console.log('unsubscribe successful');
                }).catch(function(e) {
                    // Unsubscription failed
                    console.log('unsubscribe failed', e);
                })
            })        
        });//*/
    }
});

之后,您需要在 google 开发者控制台上注册一个帐户并为 *.xxxx.com 之类的项目注册一个项目。然后您需要使用 gcm_sender_id 和 gcm_user_visible_only 获取正确的清单 json

您需要为服务器和浏览器应用程序创建一个密钥,此页面上有更多信息。

https://developers.google.com/web/updates/2015/03/push-notificatons-on-the-open-web?hl=en

用于浏览器应用程序的那个在您的清单 json 中。

然后发送推送通知你将使用这样的东西:

  function addSWmessage($args){

    $output = false;

    if(!isset($args['expiration']) || $args['expiration'] == ''){
        $args['expiration'] = date('Y-m-d H:i:s', strtotime('+7 days', time()));
    }

    $sql = sprintf("INSERT INTO `serviceworker_messages` SET title = '%s', body = '%s', imageurl = '%s', linkurl = '%s', hash = '%s', expiration = '%s'",
                    parent::escape_string($args['title']),
                    parent::escape_string($args['text']),
                    parent::escape_string($args['imageurl']),
                    parent::escape_string($args['linkurl']),
                    parent::escape_string(md5(uniqid('******************', true))),
                    parent::escape_string($args['expiration']));

    if($id = parent::insert($sql)){
        $output = $id;
    }

    return $output;

}
function pushSWmessage($args){

    //$args['messageid'] $args['userids'][]

    foreach($args['userids'] as $val){

        $sql = sprintf("SELECT messages_mobile, messages FROM `users_serviceworker_hash` WHERE users_id = '%s'",
                        parent::escape_string($val));

        if($row = parent::queryOne($sql)){
            $m1 = json_decode($row['messages'], true);
            $m1[] = $args['messageid'];
            $m2 = json_decode($row['messages_mobile'], true);
            $m2[] = $args['messageid'];

            $sql = sprintf("UPDATE `users_serviceworker_hash` SET messages = '%s', messages_mobile = '%s' WHERE users_id = '%s'",
                            parent::escape_string(json_encode($m1)),
                            parent::escape_string(json_encode($m2)),
                            parent::escape_string($val['users_id']));

            parent::insert($sql);
        }
    }

    $sql = sprintf("SELECT subscriptionID, users_id FROM `users_serviceworker_subscriptions`");

    if($rows = parent::query($sql)){

        foreach($rows as $val){
            if(in_array($val['users_id'], $args['userids'])){
                $registrationIds[] = $val['subscriptionID'];
            }
        }
        if(isset($registrationIds) && !empty($registrationIds)){
            // prep the bundle
            $msg = array
            (
                'message'       => '!',
                'title'         => '!',
                'subtitle'      => '!',
                'tickerText'    => '!',
                'vibrate'       => 1,
                'sound'         => 1,
                'largeIcon'     => '!',
                'smallIcon'     => '!'
            );

            $headers = array
            (
                'Authorization: key='.SW_API_ACCESS_KEY,
                'Content-Type: application/json'
            );

            $fields = array
            (
                'registration_ids'  => $registrationIds,
                'data'              => $msg
            );

            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
            curl_setopt($ch,CURLOPT_POST, true);
            curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch,CURLOPT_POSTFIELDS, json_encode($fields));
            curl_exec($ch);
            curl_close($ch);
        }
    }

}

不,我不知道您遇到了什么问题,但这对我来说适用于多个子域。:)

于 2015-08-07T15:04:23.567 回答