Show a error page in a PWA when it is offline - progressive-web-apps

I would like to show an error page when my PWA is offline. It's an application of only one page (index.hmtl) but in case of a user try to visit another page, show a html file called error.html.
This is the code I'm trying:
self.addEventListener('fetch', e => {
console.log('Fetch...', e);
e.respondWith(
caches.match(e.request)
.then(resultCache => {
return resultCache
})
.catch(() => cache.match('/error.html'))
)
})

The full answer here is complicated.
I do a few things.
Hook into the client online event and toggle from that
The online event is not 100% reliable as a phone may be connected to a cell tower, but no Internet connectivity. So if a fetch fails indicating we are offline I toggle the state.
Between the client layer and the service worker I post messages back and forth to indicate state changes. If the service worker knows the device is offline I intercept all document requests going to the cloud and return an offline response page.
I also use the offline state and inject a CSS class in the body.classList array to toggle some sort of visual to the user. One thing I love to do is apply a grayscale mask over the entire page like FlipKart does. But it could be a variety of visual queues.

Related

Is there a way to capture & handle "next" and "previous” using Google Actions with Actions SDK as the fulfillment tool When Media Response was sent?

I'm using the Media Response to play audio in my Actions SDK (Action SDK is being used as the Fulfillment tool in my Actions Console) driven Action. At the end of each audio clip, I'm using the MEDIA_STATUS callback to advance to another mp3 file in a predefined playlist. As a result, users should be able to navigate forwards / backwards.
When testing on my Google Home mini, Google Assistant on Android and Smart Display, I can intercept "next" and advance to the next audio clip (it sends a request with intent of type MEDIA_STATUS). However, I can't properly intercept "previous" Whenever I try, the audio will restart. Real devices seems to be handling this intent on it's own and does not throw any console output (as my webhook is not accessed at all).
Dialog Flow seem to handle "next" and "previous" as follow up intents, but I need to do the same without using Dialog Flow as the Fulfillment tool.
Can anyone please help with this particular problem?
Currently only a FINISHED event is supported for the Media Response. So, you would not be able to handle distinguish between next and previous.
Referring to #Leon Nicholls answer, I am really confused. I followed his Google Audioplayer tutorial/guide which links to an audioplayer template action
You can still download it, and if you unzip it, you will see code that is put there specifically to handle previous and next tracks.
Now it appears Leon is saying that it can't handle previous and next by voice (but buttons appear to work).
Here is the sample code below. There are links to tutorial actions in it, but now all the content has been removed. I simply need blind people to be able to select and play various bit of audio, too long for SSML, which must be navigable (at least next and pause/resume later) may be part of a playlist. How do I achieve this? Suggesting "Media Partner" or "Podcast" is not a solution as neither available in the UK.
// Handle the More/Yes/Next intents
app.intent(['More', 'Yes', 'Next'], (conv) => {
console.log(`More: fallbackCount=${conv.data.fallbackCount}`);
nextTrack(conv, false);
});
// Handle the Repeat/Previous intent
app.intent(['Repeat', 'Previous'], (conv) => {
console.log(`Repeat: ${conv.user.storage.track}`);
nextTrack(conv, false, true);
});
// Select the next track to play from the data
const nextTrack = (conv, intro, backwards) => {
console.log(`nextTrack: ${conv.user.storage.track}`);
let track = data[0];
// Persist the selected track in user storage
// https://developers.google.com/actions/assistant/save-data#save_data_across_conversations
if (conv.user.storage.track) {
conv.user.storage.track = parseInt(conv.user.storage.track, 10);
if (backwards) {

Is there a smart possibility to get API results without sending requests every second? [VueJS | Vuetify]

So I made a website to show which services on my server are running and which are offline.
The site is an Vuetify App running in a docker container. My services are monitored via UptimeRobot.
Currently I use:
created: function () {
this.interval = setInterval(() => this.getStatuses(), 1000);
},
To trigger my API request function every second to update the status of my services.
But is there some smarter possibility to only update on change and not request every second to see if something happened?
Like I send one request to get the status and then receive a message when something changed? I hope you can understand, whats my problem. It's hard to decribe.
Yes you can by firing an event. for example:
in your app.js
window.Fire = new Vue();
For example here you create a user then you want to update table after creating a new user, Follow these steps:
createUser(){
// FireUpdate is your fire name, you can give it any name you want!
// Call this after you post something to specific route.
Fire.$emit('FireUpadte');
}
Then you will load new users using this approach:
created(){
// Load new Users after created.
Fire.$on('FireUpadte', () => { this.createUser(); });
}
For more information check this video: https://www.youtube.com/watch?v=DHuTkJzH2jI&list=PLB4AdipoHpxaHDLIaMdtro1eXnQtl_UvE&index=20
What you're looking for are websockets. You establish a websocket connection and it stays open, allowing the server to notify the web app when something changes.
You can run your own socket.io server on a Node.js backend or use a service like Pusher.com (very cheap, free tier is pretty big).
I highly recommend going the Pusher.com route, they also have great tutorials ; )
https://pusher.com

Facebook pixel events call from server

I have absolutelly the same question as dan here - Facebook conversion pixel with "server to server" option . There was written, that there was no way, but it was 2013, so I hope something changed.
So, is there any way to call facebook pixel events (e.g. CompleteRegistration) from server side now?
I can describe situation in more details. Imagine, that user visits our site, where fb pixel tracks 'PageView' of course. When user passes form and sends his phone number, we call 'Lead' event. But then we need to track one more event, when our manager successfully confirmes this user! Of course, it happens on other computer and so on, so there is no idea, how to "connect" to base user.
I've seen a lot of documentation departments like this, but I can't fully understand even if it's possible or not.
Logically, we need to generate specific id for user (or it can be phone number really), when 'Lead' event is called. Then, we should use this id to 'CompleteRegistration' for that user. But I can't understand, how to do it technically.
It would be gratefull, if somebody could explain it.
P.S. As I understand, it is fully available in API for mobile apps. Is it ok idea to use it for our situation, if there is no other solution?
Use Offline Conversions to record events that happen after a user has left your website. Logging these conversions, technically, is very easy. Setting everything up takes a little effort
tldr; check the code below
Follow setup steps in the FB docs (Setup steps 1-5) which are:
Setup facebook Business Manager account
Add a new app to Business Manager account
Create an Ad account, if you don't already have one
Create a System User for the ad account
After the setup, follow Upload Event Data steps on the same page, steps 1-3 to create an offline event set and associate it with your ad. These can be carried out in the Graph API Explorer by following the links in the examples. These can be done programmatically, but is out of the scope of making the event calls from the server for one campaign.
Once you have created the event set, then you can upload your CompleteRegistration events!
You will need to make a multipart form data request to FB, the data key will be an array of your conversion events. As #Cbroe mentioned, you must hash your match keys (the data you have available about your user to match them with a FB user) before sending to FB. The more match keys you are able to provide, the better chance at matching your user. So if you can get their email and phone at the same time, you're much more likely to match your user.
Here's an example of the call to FB using node.js:
var request = require('request')
// The access token you generated for your system user
var access_token = 'your_access_token'
// The ID of the conversion set you created
var conversionId = 'your_conversion_set_id'
var options = {
url: 'https://graph.facebook.com/v2.12/' + conversionId + '/events',
formData: {
access_token: access_token,
upload_tag: 'registrations', //optional
data: [{
match_keys: {
"phone": ["<HASH>", "<HASH>"]
},
currency: "USD",
event_name: "CompleteRegistration",
event_time: 1456870902,
custom_data: { // optional
event_source: "manager approved"
},
}]
}
}
request(options, function(err, result) {
// error handle and check for success
})
Offline Conversion Docs
Facebook has now a Server-Side API: https://developers.facebook.com/docs/marketing-api/server-side-api/get-started
Implementing this is similar to implementing the offline events outlined in the accepted answer.
Keep in mind that it will always be cumbersome to track and connect events from the browser and from your server. You need to share a unique user id between the browser and server, so that Facebook (or any other analytics provider) will know that the event belongs to the same user.
Tools like mixpanel.com and amplitude.com may be more tailored to your needs, but will get very expensive once you move out of the free tier (100+ EUR at mixpanel, 1000+ EUR at Amplitude, monthly). Those tools are tailored towards company success, whereas Facebook is tailored towards selling and measuring Facebook ads.

Real time model events in Sails.js 0.10-rc5

I've been playing around with building some realtime functionality using Sails.js version 0.10-rc5 (currently the #beta release).
To accomplish anything, i've been following the sweet SailsCast tutorial on this subject (sailsCast link)
It talks about subscribing to a model via a 'subscribe' action within the model's controller. Then listening to it at the client side, waiting for the server to emit messages. Quite straightforward, although I do not seem to receive any messages.
I'm trying to do this to get real-time updates on anything that changes in my User models, or if new ones get created.. So I can display login status etc. in real time. Pretty much exactly the stuff that's explained in the sailsCast.
In my terminal i'll get two things worth noticing, of which the first is the following:
debug: Deprecated: `Model.subscribe(socket, null, ...)`
debug: See http://links.sailsjs.org/docs/config/pubsub
debug: (⌘ + double-click to open link from terminal)
debug: Please use instance rooms instead (or raw sails.sockets.*() methods.)
It seems like the 'subscribe' method has been deprecated. Could anybody tell me if that's correct, and tell me how to fix this? I've been checking out the reference to the documentation in the debug message, although it just points me to the global documentation page. I've been searching for an answer elsewhere, but haven't found anything useful.
The second message I'm getting is:
warn: You are trying to render a view (_session/new), but Sails doesn't support rendering views over Socket.io... yet!
You might consider serving your HTML view normally, then fetching data with sockets in your client-side JavaScript.
If you didn't intend to serve a view here, you might look into content-negotiation
to handle AJAX/socket requests explictly, instead of `res.redirect()`/`res.view()`.
Now, i'm quite sure this is because I have an 'isAuthenticated' policy added to all of my controllers and actions. When a user is not authenticated, it'll redirect to a session/new page. Somebody must log in to be able to use the application. When I remove the 'isAuthenticated' policy from the 'subscribed' action, the warnings disappear. Although that means anyone will get updates via sockets (when I get it to work), even when they're logged out. - I don't really feel like people just sitting at the login screen, fishing out the real time messages which are intended only for users who are logged in.
Can anyone help me getting the real time updates to work? I'd really appreciate!
As far as the socket messages not being received, the issue is that you're following a tutorial for v0.9.x, but you're using a beta version of Sails in which PubSub has gone through some changes. That's covered in this answer about the "create" events not being received.
Your second issue isn't about sockets at all; you'll just need to reconsider your architecture a bit. If you want to to use socket requests to sign users in, then you'll have to be more careful about redirecting them because, as the message states, you can't render a view over a socket. Technically you could send a bunch of HTML back to the client over a socket, and replace your current page with it, but that's not very good practice. What you can do instead is, in your isAuthenticated policy, check whether the request is happening via sockets (using req.isSocket) and if so, send back a message that the front end can interpret to mean, "you should redirect to the login page now". Something like:
module.exports = function (req, res, next) {
if ([your auth logic here]) {
return next();
}
else {
if (req.isSocket) {
return res.json({status: 403, redirectTo: "/session/new"});
} else {
return res.redirect("/session/new");
}
}
}

grails+spring-security-facebook listen to login success event

im a newbie both in spring security and spring-security-facebook and in an app that we are building we have to couple them.Everything is working well i will need to know the way to listen to the facebook login success event. is there some one that already did a stuff that impose him to catch the facebook event success?? I need that because in the begining of the app (before adding the spring -security-Facebook plugin ); we have a special behaviour attached to the "grails.plugins.springsecurity.onInteractiveAuthenticationSuccessEvent" event (configured in the config.groovy file) and we have to execute the same special behaviour when the user connect with facebook account. Is there an event (extending springsecurity kinds of events) that we have to listen to?
any idea ??
Ps: when searching for solution we found a way to catch the FB js Events and work around to reach what we want as result but we would as possible to want to not go that way ....
The problem with it that current Spring Security Facebook authenticates user on each request (by listening to FB cookie, transparently), so you'll get this event on each request. Probably it's not what you want, right? It the same as having a filter on each request.
Btw, you can handle situation when user login into your app first time, but implementing onCreate(user, token) or afterCreate(user, token) in service FacebookAuthService (you have to create such service at this case)
Example:
File grails-app/services/FacebookAuthService.groovy:
class FacebookAuthService {
void afterCreate(def user, def token) {
log.info("New user!") //or any code there
}
}