问题描述
我有两个子域: : 和 。 所以我的问题是:
1)。 是否可以从为注册服务人员? 如果是,那怎么办?
2)。 如果 ( http不安全),则无论如何在iframe或类似的东西上从为注册服务工作者。
这是一个真实的情况,我面临着我的多个子域。 任何帮助表示赞赏。 提前致谢。
1楼
Jeff Posnick
16
已采纳
2015-08-07 17:11:13
以下是一些我认为应该解决您在问题中提出的各点的一般性答案:
每个注册的服务人员都有一个关联的 ,该规定了服务人员可以控制的网页集。 服务工作者的
scope
是一个URL,并且该URL必须与注册该服务工作者的页面具有相同的来源,并且必须是与该页面相同的路径级别相对应的URL或一个或多个路径降低水平。 默认scope
与服务工作程序脚本的位置对应于相同的路径级别。 由于存在此限制,因此无法从一个(子)域上的页面调用navigator.serviceWorker.register(...)
,而最终只能得到控制另一个(子)域上的页面的服务工作者。有一定的限制,以防止您在
http:
页面上引发https:
<iframe>
并使用它来注册服务工作者。 请参阅尽管我不知道这与您的问题直接相关,但在服务工作者代码中为
http:
资源显式调用fetch()
会导致当前版本的Chrome失败,因为混合内容的fetch()
不是允许在服务人员中使用。 我不知道这件事是否100%解决了, 仍然有用。
如果您的页面同时存在于abc.123.com
和xyz.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
。
例如,这是通过 。
2楼
Vivek Pratap Singh
5
2016-10-07 05:17:38
Service Worker scripts must be hosted at the same origin (Protocol + Domain name + Port).
每个子域都被认为是不同的来源,因此,您将需要为每个子域注册一个服务工作者。
这些工作者中的每一个都有自己的cache
和scope
。
3楼
Rick
0
2018-12-29 10:06:10
尝试使用Ngnix proxy_pass。 这项工作对我来说。
4楼
Alanthir
-1
2015-08-07 15:04:23
不好,我误会了一点。 好吧,这是代码
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 Developer Console上注册一个帐户,并为* .xxxx.com之类的项目注册一个项目。 然后,您需要使用gcm_sender_id和gcm_user_visible_only获取正确的清单json
您需要为服务器和浏览器应用程序都创建一个密钥,此页面上有更多信息。
用于浏览器应用程序的一个放在清单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);
}
}
}
不,我不知道您遇到了什么问题,但这对我来说适用于多个子域。 :)