如何注册来自不同子域的服务工作者
how to register a service worker from different sub domain
我有两个子域:https://abc.xxxx.com and https://xyz.xxxx.com。所以我的问题:
1). is it possible to register a service worker for
https://xyz.xxxx.com from https://abc.xxxx.com ? if yes then how?
2). if http://abc.xxxx.com (http insecure) then anyway to register
a service worker for https://xyz.xxxx.com from http://abc.xxxx.com like in iframe or something....
这是一个真实的情况,我面临着我的多个子域。任何帮助表示赞赏。提前致谢。
不好意思,我有点误会了。嗯,这是代码
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.');
}
那么这是您订阅/取消订阅的活动 -ish
// 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);
}
}
}
不,我不知道您遇到了什么问题,但这对我来说适用于多个子域。 :)
以下是我认为应该解决您在问题中提出的各个要点的一些一般性答案:
每个注册的 service worker 都有一个关联的 scope
,它规定了 service worker 可以控制的网页集。 Service Worker 的 scope
是 URL,并且 URL 必须与注册 Service Worker 的页面具有相同的来源,并且必须是 URL对应于与页面相同的路径级别或向下一个或多个级别的路径。默认 scope
对应于与服务工作者脚本位置相同的路径级别。由于此限制,不可能从一个(子)域上的页面调用 navigator.serviceWorker.register(...)
并最终得到一个控制另一个(子)域上的页面的服务工作者。
有一些限制可以防止您在 http:
页面上抛出 https:
<iframe>
并使用它来注册服务工作者。参见
虽然我不知道它与您的问题直接相关,但在您的服务工作者代码中为 http:
资源显式调用 fetch()
将导致失败Chrome 的当前版本,因为混合内容 fetch()
在 service worker 中是不允许的。我不知道这方面的事情是否已 100% 解决,this open bug 仍然相关。
如果您的页面同时存在于 abc.123.com
和 xyz.123.com
上,并且您希望两组页面都由 service worker 控制,那么您需要有两个单独的 service worker 注册。每次注册都需要为您的服务工作者 JS 文件的副本托管在与顶级页面对应的相应域上,并且所有页面和服务工作者脚本都需要通过 https:
.[=34= 访问]
话虽这么说,您 可以 通过在页面上包含跨域 <iframe>
来启动不同域的服务工作者注册,但是主机页面和 <iframe>
需要通过 https:
提供。正常的 service worker 范围限制适用,因此,例如,如果你想为另一个域注册一个 service worker,它将覆盖整个 https://other-domain.com/
范围,你需要确保 service worker 脚本的位置being registered 在顶层,例如https://other-domain.com/service-worker.js
,而不是 https://other-domain.com/path/to/service-worker.js
。这是 AMP project via the <amp-install-serviceworker>
element.
使用的方法
Service Worker scripts must be hosted at the same origin (Protocol + Domain name + Port).
每个子域都被认为是不同的来源,因此,您需要为每个子域注册一个 service worker。这些工人中的每一个都会有自己的 cache
和 scope
.
尝试使用 Nginx proxy_pass。这对我有用。
我有两个子域:https://abc.xxxx.com and https://xyz.xxxx.com。所以我的问题:
1). is it possible to register a service worker for https://xyz.xxxx.com from https://abc.xxxx.com ? if yes then how?
2). if http://abc.xxxx.com (http insecure) then anyway to register a service worker for https://xyz.xxxx.com from http://abc.xxxx.com like in iframe or something....
这是一个真实的情况,我面临着我的多个子域。任何帮助表示赞赏。提前致谢。
不好意思,我有点误会了。嗯,这是代码
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.');
}
那么这是您订阅/取消订阅的活动 -ish
// 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);
}
}
}
不,我不知道您遇到了什么问题,但这对我来说适用于多个子域。 :)
以下是我认为应该解决您在问题中提出的各个要点的一些一般性答案:
每个注册的 service worker 都有一个关联的
scope
,它规定了 service worker 可以控制的网页集。 Service Worker 的scope
是 URL,并且 URL 必须与注册 Service Worker 的页面具有相同的来源,并且必须是 URL对应于与页面相同的路径级别或向下一个或多个级别的路径。默认scope
对应于与服务工作者脚本位置相同的路径级别。由于此限制,不可能从一个(子)域上的页面调用navigator.serviceWorker.register(...)
并最终得到一个控制另一个(子)域上的页面的服务工作者。有一些限制可以防止您在
http:
页面上抛出https:
<iframe>
并使用它来注册服务工作者。参见虽然我不知道它与您的问题直接相关,但在您的服务工作者代码中为
http:
资源显式调用fetch()
将导致失败Chrome 的当前版本,因为混合内容fetch()
在 service worker 中是不允许的。我不知道这方面的事情是否已 100% 解决,this open bug 仍然相关。
如果您的页面同时存在于 abc.123.com
和 xyz.123.com
上,并且您希望两组页面都由 service worker 控制,那么您需要有两个单独的 service worker 注册。每次注册都需要为您的服务工作者 JS 文件的副本托管在与顶级页面对应的相应域上,并且所有页面和服务工作者脚本都需要通过 https:
.[=34= 访问]
话虽这么说,您 可以 通过在页面上包含跨域 <iframe>
来启动不同域的服务工作者注册,但是主机页面和 <iframe>
需要通过 https:
提供。正常的 service worker 范围限制适用,因此,例如,如果你想为另一个域注册一个 service worker,它将覆盖整个 https://other-domain.com/
范围,你需要确保 service worker 脚本的位置being registered 在顶层,例如https://other-domain.com/service-worker.js
,而不是 https://other-domain.com/path/to/service-worker.js
。这是 AMP project via the <amp-install-serviceworker>
element.
Service Worker scripts must be hosted at the same origin (Protocol + Domain name + Port).
每个子域都被认为是不同的来源,因此,您需要为每个子域注册一个 service worker。这些工人中的每一个都会有自己的 cache
和 scope
.
尝试使用 Nginx proxy_pass。这对我有用。