-1

When a user clicks...

<%= 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>

he should be taken through...

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

but instead nothing happens. The .webpush-button javascript never kicks in. I put it in two places and it still has no effect...

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>

Now based on the tutorial and git code I used... the subscription should be gathered from the serviceworker so then why am I still getting a nil error?

I'm using serviceworker & webpush gems and followed this VAPID tutorial.

Not a duplicate. The other question is focused on params. This one is focused on javascript not triggering.

AnthonyGalli.com
  • 2,796
  • 5
  • 31
  • 80
  • Possible duplicate of [subscription params nil for web push serviceworker?](http://stackoverflow.com/questions/43572177/subscription-params-nil-for-web-push-serviceworker) – Roman Kiselenko Apr 24 '17 at 05:32

1 Answers1

1

First, you should only put the javascript at one place.

Second, add the .webpush-button click method after page be ready

$(document).on('ready page:load', function () {

});

And in the chrome dev tools, Tab Event Listeners, check if the html element has click event.

  • Yes it does have click event with `button.webpush-button`. With the adjustment I made from your answer the javascript still doesn't trigger. I also removed the duplication from application.js – AnthonyGalli.com Apr 24 '17 at 05:42
  • em..you can also add the `console.log` before your method, if it show the log, then the javascript is `triggered`, just your code logic is wrong. – seaify - Freelancer Apr 24 '17 at 05:49