每次我嘗試啓動我的服務器我得到這個錯誤...web推送serviceworker未定義的方法錯誤?
undefined method `post' for main:Object (NoMethodError)
application.rb中
post "/push" do
Webpush.payload_send(
endpoint: "https://fcm.googleapis.com/gcm/send/eah7hak....",
message: "A message",
p256dh: "BO/aG9nYXNkZmFkc2ZmZHNmYWRzZmFl...",
auth: "aW1hcmthcmFpa3V6ZQ==",
vapid: {
subject: "mailto:[email protected]",
public_key: ENV['VAPID_PUBLIC_KEY'],
private_key: ENV['VAPID_PRIVATE_KEY']
}
)
end
上午我把代碼塊中錯誤的地方?我認爲app.rb
是一回事application.rb
截圖是從git的教程:https://github.com/zaru/webpush。
我試圖用VAPID和寶石實現瀏覽器通知webpush
& serviceworker-rails
。
的application.js
// Register the serviceWorker script at /serviceworker.js from our server if supported
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/serviceworker.js')
.then(function(reg) {
console.log('Service worker change, registered the service worker');
});
}
// Otherwise, no push notifications :(
else {
console.error('Service worker is not supported in this browser');
}
// When serviceWorker is supported, installed, and activated,
// subscribe the pushManager property with the vapidPublicKey
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager
.subscribe({
userVisibleOnly: true,
applicationServerKey: window.vapidPublicKey
});
});
$('.webpush-button').on('click', (e) => {
navigator.serviceWorker.ready
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((subscription) => {
$.post('/push', {
subscription: subscription.toJSON(),
message: 'You clicked a button!'
});
});
});
});
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
console.error("This browser does not support desktop notification");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
console.log("Permission to receive notifications has been granted");
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
console.log("Permission to receive notifications has been granted");
}
});
}
是的,你把代碼放在錯誤的地方,'app.rb'不適用於Rails應用程序。嘗試在軌道控制器中使用該代碼。 – Gerry
這一切都取決於你的導軌設計,如果你想成爲你的根頁面,然後創建根路線,否則任何路線將做到這一點。方法名稱(aka action)也是如此。 – Gerry