As soon as a person comes to my site they are confronted with...
But I only want that popup to occur after a user clicks "Push" so that the user may understand the context of the request.
How to only trigger the browser notification request upon a user clicking "Push"?
I implemented push via serviceworker gem , webpush gem , VAPID tutorial .
<%= form_for(@challenge) do |f| %>
<%= f.check_box :push %>
<label for="challenge_push">Push <%= image_tag "laptop.png" %></label>
<% end %>
application.js
// 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");
}
});
}
Just Wrap your notification asking part from application.js with function. Then add that function to click handlers of Push button.
const askForNotification = () => {
//you code here
}
pushButton.addEventListener("click", askForNotification)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.