Skip to content

Commit

Permalink
Add alternative method to pass the VAPID public key to JavaScript (cl…
Browse files Browse the repository at this point in the history
…oses #11)

Co-authored-by: rossta  <ross@rossta.net>
  • Loading branch information
collimarco and rossta committed Jan 30, 2024
1 parent f140f28 commit 5372677
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,16 @@ navigator.serviceWorker.register('/service-worker.js')

### Subscribing to push notifications

The VAPID public key you generated earlier is made available to the client as a `UInt8Array`. To do this, one way would be to expose the urlsafe-decoded bytes from Ruby to JavaScript when rendering the HTML template.
The VAPID public key that you generated earlier needs to be made available to JavaScript, which can be done in many ways, for example with a fetch request or when rendering the HTML template in Ruby:

```javascript
window.vapidPublicKey = new Uint8Array(<%= Base64.urlsafe_decode64(ENV['VAPID_PUBLIC_KEY']).bytes %>);
```erb
<script>
// Make the VAPID public key available to the client as a Uint8Array
window.vapidPublicKey = new Uint8Array(<%= Base64.urlsafe_decode64(ENV['VAPID_PUBLIC_KEY']).bytes %>)
// Or you can pass it as a string if you prefer
window.vapidPublicKey = "<%= ENV['VAPID_PUBLIC_KEY'].delete('=') %>"
</script>
```

Your JavaScript code uses the `pushManager` interface to subscribe to push notifications, passing the VAPID public key to the subscription settings.
Expand Down

0 comments on commit 5372677

Please sign in to comment.