如何使用javascript点击触发POST

How to use javascript click to trigger POST

当用户点击...

<%= content_tag(:button, "Send", class: "webpush-button") %>
# Previous Attempt: <%= button_to 'send', class: "webpush-button" %>

<script>
  $('.webpush-button').on('click', (e) => {
    navigator.serviceWorker.ready
    .then((serviceWorkerRegistration) => {
      serviceWorkerRegistration.pushManager.getSubscription()
      .then((subscription) => {
        $.post("/post", {
          subscription: subscription.toJSON(),
          message: 'You clicked a button!'
        });
      });
    });
  });
</script>

他应该通过...

class PushNotificationsController < ApplicationController
  def push
    Webpush.payload_send(
      message: params[:message],
      endpoint: params[:subscription][:endpoint],
      p256dh: params[:subscription][:keys][:p256dh],
      auth: params[:subscription][:keys][:auth],
      vapid: {
        subject: "mailto:sender@example.com",
        public_key: ENV['VAPID_PUBLIC_KEY'],
        private_key: ENV['VAPID_PRIVATE_KEY']
      }
    )
  end
end

但是什么也没发生。 .webpush-button javascript 从来没有踢过。我把它放在两个地方,它仍然没有效果...

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");
    }
  });
}

application.html.erb

<script>
  window.vapidPublicKey = new Uint8Array("<%= @decodedVapidPublicKey %>");
</script>

现在基于 tutorial and git code I used... the subscription should be gathered from the serviceworker 那么为什么我仍然收到 nil 错误?

我正在使用 serviceworker & webpush gems and followed this VAPID tutorial

不是重复的。另一个问题集中在参数上。这个重点是 javascript 不触发。

首先,你应该只把 javascript 放在一个地方。

其次,在页面ready

之后添加.webpush-button click方法
$(document).on('ready page:load', function () {

});

然后在 chrome 开发工具中,Tab Event Listeners,检查 html 元素是否有点击事件。