Javascript 如何自定义浏览器webpush通知正文&;偶像
如何根据Javascript 如何自定义浏览器webpush通知正文&;偶像,javascript,jquery,ruby-on-rails,push-notification,service-worker,Javascript,Jquery,Ruby On Rails,Push Notification,Service Worker,如何根据@challenge.image和@challenge.description动态定制浏览器通知图标和正文 我通过单击webpush button得到弹出通知,但只有消息的标题在动态变化。如何使它也适用于主体和图标 challenges/show.html.erb <script> $('.webpush-button').on('click', (e) => { navigator.serviceWorker.ready .then((servi
@challenge.image
和@challenge.description
动态定制浏览器通知图标
和正文
我通过单击webpush button
得到弹出通知,但只有消息的标题
在动态变化。如何使它也适用于主体
和图标
challenges/show.html.erb
<script>
$('.webpush-button').on('click', (e) => {
navigator.serviceWorker.ready
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((subscription) => {
$.post('/push', {
subscription: subscription.toJSON(),
message: "<%= @challenge.name %>", # This works dynamically for the title, but how can I get message to also dynamically send body and icon so I can use <%= @challenge.image %> for icon and <%= @challenge.description %> for body?
});
});
});
});
</script>
console.log('[Service Worker] Hello world!');
var CACHE_VERSION = 'v1';
var CACHE_NAME = CACHE_VERSION + ':sw-cache-';
function onInstall(event) {
console.log('[Serviceworker]', "Installing!", event);
event.waitUntil(
caches.open(CACHE_NAME).then(function prefill(cache) {
return cache.addAll([
// make sure serviceworker.js is not required by application.js
// if you want to reference application.js from here
'<%#= asset_path "application.js" %>',
'<%= asset_path "application.css" %>',
'/offline.html',
]);
})
);
}
function onActivate(event) {
console.log('[Serviceworker]', "Activating!", event);
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
return cacheName.indexOf(CACHE_VERSION) !== 0;
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
}
// Borrowed from https://github.com/TalAter/UpUp
function onFetch(event) {
event.respondWith(
// try to return untouched request from network first
fetch(event.request).catch(function() {
// if it fails, try to return request from the cache
return caches.match(event.request).then(function(response) {
if (response) {
return response;
}
// if not found in cache, return default offline content for navigate requests
if (event.request.mode === 'navigate' ||
(event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
console.log('[Serviceworker]', "Fetching offline content", event);
return caches.match('/offline.html');
}
})
})
);
}
self.addEventListener("push", (event) => {
let title = (event.data && event.data.text()) || "Yay a message";
let body = "We have received a push message";
let icon = '/assets/default.png';
event.waitUntil(
self.registration.showNotification(title, { title,body, icon })
)
});
self.addEventListener('install', onInstall);
self.addEventListener('activate', onActivate);
self.addEventListener('fetch', onFetch);
serviceworker.js.erb
<script>
$('.webpush-button').on('click', (e) => {
navigator.serviceWorker.ready
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((subscription) => {
$.post('/push', {
subscription: subscription.toJSON(),
message: "<%= @challenge.name %>", # This works dynamically for the title, but how can I get message to also dynamically send body and icon so I can use <%= @challenge.image %> for icon and <%= @challenge.description %> for body?
});
});
});
});
</script>
console.log('[Service Worker] Hello world!');
var CACHE_VERSION = 'v1';
var CACHE_NAME = CACHE_VERSION + ':sw-cache-';
function onInstall(event) {
console.log('[Serviceworker]', "Installing!", event);
event.waitUntil(
caches.open(CACHE_NAME).then(function prefill(cache) {
return cache.addAll([
// make sure serviceworker.js is not required by application.js
// if you want to reference application.js from here
'<%#= asset_path "application.js" %>',
'<%= asset_path "application.css" %>',
'/offline.html',
]);
})
);
}
function onActivate(event) {
console.log('[Serviceworker]', "Activating!", event);
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
return cacheName.indexOf(CACHE_VERSION) !== 0;
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
}
// Borrowed from https://github.com/TalAter/UpUp
function onFetch(event) {
event.respondWith(
// try to return untouched request from network first
fetch(event.request).catch(function() {
// if it fails, try to return request from the cache
return caches.match(event.request).then(function(response) {
if (response) {
return response;
}
// if not found in cache, return default offline content for navigate requests
if (event.request.mode === 'navigate' ||
(event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
console.log('[Serviceworker]', "Fetching offline content", event);
return caches.match('/offline.html');
}
})
})
);
}
self.addEventListener("push", (event) => {
let title = (event.data && event.data.text()) || "Yay a message";
let body = "We have received a push message";
let icon = '/assets/default.png';
event.waitUntil(
self.registration.showNotification(title, { title,body, icon })
)
});
self.addEventListener('install', onInstall);
self.addEventListener('activate', onActivate);
self.addEventListener('fetch', onFetch);
我实现了push via,.self.addEventListener中的
事件.data
对象(“push”,(event)=>{…},有一个方法json()
,该方法将事件.data
值转换为json
仅当发送的数据采用正确的json格式时,此操作才有效。
以下是我如何使用web推送的示例:
self.addEventListener("push", function onPush(event) {
var data = event.data.json()
event.waitUntil(self.registration.showNotification(data.message.title, {
body: data.message.body,
icon: data.message.icon,
actions: [
{ action: 'Button one', title: "Button one text" },
{ action: 'Button two', title: "Button two text" }
]
}));
});
以下是my user.rb模型中的一个方法:
def send_web_push(title: , body: )
# the web_push is a payload with I save to the user record,
# that's allow me to send web push with background worker.
payload = {
endpoint: web_push['endpoint'],
keys: {
auth: web_push['auth'],
p256dh: web_push['p256dh']
}
}
push = WebPush.new(payload)
push.set_vapid_details(
'mailto:support@awesomesupewebapp.com',
Rails.application.secrets.web_push_public_key,
Rails.application.secrets.web_push_private_key
)
# below is a `:message` key in json format
push.send_notification({
message: {
title: title,
body: body,
icon: "/this_is_my_icon.png"
}
}.to_json)
end
我使用了一些其他的RubyGem进行web_推送,但我认为这是很常见的。从该示例中,您应该了解如何更改主体、标题和图标键 self.addEventListener(“push”,(event)=>{…}中的
event.data
对象有一个方法json()
,该方法将event.data
值转换为json
仅当发送的数据采用正确的json格式时,此操作才有效。
以下是我如何使用web推送的示例:
self.addEventListener("push", function onPush(event) {
var data = event.data.json()
event.waitUntil(self.registration.showNotification(data.message.title, {
body: data.message.body,
icon: data.message.icon,
actions: [
{ action: 'Button one', title: "Button one text" },
{ action: 'Button two', title: "Button two text" }
]
}));
});
以下是my user.rb模型中的一个方法:
def send_web_push(title: , body: )
# the web_push is a payload with I save to the user record,
# that's allow me to send web push with background worker.
payload = {
endpoint: web_push['endpoint'],
keys: {
auth: web_push['auth'],
p256dh: web_push['p256dh']
}
}
push = WebPush.new(payload)
push.set_vapid_details(
'mailto:support@awesomesupewebapp.com',
Rails.application.secrets.web_push_public_key,
Rails.application.secrets.web_push_private_key
)
# below is a `:message` key in json format
push.send_notification({
message: {
title: title,
body: body,
icon: "/this_is_my_icon.png"
}
}.to_json)
end
我使用了一些其他的RubyGem进行web_推送,但我认为这是很常见的。从该示例中,您应该了解如何更改主体、标题和图标键 查看
<%= content_tag(:button, "Foo", class: "webpush-button") %>
<script>
$('.webpush-button').on('click', (e) => {
navigator.serviceWorker.ready
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((subscription) => {
$.post('/push', {
subscription: subscription.toJSON(),
message: "<%= @challenge.name %>",
body: "<%= @challenge.why %>",
icon: "/assets/default.png"
});
});
});
});
</script>
查看
<%= content_tag(:button, "Foo", class: "webpush-button") %>
<script>
$('.webpush-button').on('click', (e) => {
navigator.serviceWorker.ready
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((subscription) => {
$.post('/push', {
subscription: subscription.toJSON(),
message: "<%= @challenge.name %>",
body: "<%= @challenge.why %>",
icon: "/assets/default.png"
});
});
});
});
</script>
就像
user.send\u web\u push(title:'Here is title',body:'Here is body')
我只展示了一个示例,这意味着您的代码可以是其他代码。这是我的项目中实际工作代码的一个示例。我不是你的调试工具或开发IDE。这里有一个宝石,我正在用你能做的最好的感谢,它是批准或投票的答案。不需要文字,做一件事。像那样用户。发送\u web\u推送(标题:'这里是标题',正文:'这里是正文')
我只展示了一个例子,这意味着你的代码可以是其他的。这是我的项目中实际工作代码的一个示例。我不是你的调试工具或开发IDE。这里有一个宝石,我正在用你能做的最好的感谢,它是批准或投票的答案。不需要言语,做一件事。