I am using the 'Web push notificatoins API' to send notifications from my server to my website.
Long story short - the notifications are received and shown by all major browsers except firefox android (ios untested). I suspect the service worker file to be the culprit but have no idea how to debug see/log its errors / messages.
The service_worker.js :
self.addEventListener('push', function (event) {
if (!(self.Notification && self.Notification.permission === 'granted')) {
console.log('back) ;
return;
}
const sendNotification = body => {
const title = "BTC changed - coinvalue.me";
return self.registration.showNotification(title, {
body,
});
};
if (event.data) {
const message = event.data.text();
event.waitUntil(sendNotification(message));
}
});
Question: How to debug the results of this file? Firefox WebIDE doesn't show any console.log()
Edit : Firefox version 54.0.11 on android 4.2.1
Related
I am using FCM for web push notifications.
All worked fine until suddenly Firefox stopped delivering push notifications except the page is open in the browser.
If the page is loaded and not in focus, notifications come in. I console.log()'d the onBackgroundMessage payload and I can confirm that the service worker receives it. But if I close that tab and send a push notification, it does not receive it.
The same setup works on Chrome, Opera, and Edge just fine no errors. Is there something with firefox?
Firefox version: 88.0.1 (64-bit)
in my Service Worker I have:
messaging.onBackgroundMessage(function (payload) {
// Customize notification here
var action_label;
if('action_label' in payload.data){
action_label = payload.data.action_label;
} else{
action_label = "Details";
}
const notificationTitle = payload.data.title;
const notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
requireInteraction: true,
data: {
click_action: payload.data.click_action,
url:payload.data.click_action
},
actions: [
{
action: "open_url", title: action_label
}
]
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
This had to do with Firefox quitting instead closing, obtainable in MacBooks.
Not a real technical issue.
I have a web app that needs to execute specific code if it is running in Microsoft Teams, however I haven't yet figured out if there is any way to tell if your app is running in teams. Any ideas or insight?
edit:
for anyone wondering we ended up using a combination of the two answers below, on app start it will check the url of the app to see if it contains "/teams". The teams app is told specifically to point to {app_name}/teams, if this case is true it will run the following code block:
import * as microsoftTeams from '#microsoft/teams-js';
if (window.location.pathname.includes('teams')) {
microsoftTeams.initialize(() => {
microsoftTeams.getContext(context => {
store.dispatch(teamsDetected(context.hostClientType!));
try {
microsoftTeams.settings.registerOnSaveHandler(saveEvent => {
microsoftTeams.settings.setSettings({
websiteUrl: window.location.href,
contentUrl: `${window.location.href}&teams`,
entityId: context.entityId,
suggestedDisplayName: document.title
});
saveEvent.notifySuccess();
});
microsoftTeams.settings.setValidityState(true);
} catch (err) {
console.error('failed to set teams settings')
}
});
});
}
As you have probably experienced, a call to microsoftTeams.getContext(...) never returns if you are not in Teams.
So I have a flag that I monitor with a setInterval and if this._teamsContext is truthy, and has sane values; and only if if has this._hasAttemptedConnection
It is a bit of a round-a-bout way.
Another mechanism I implemented a little later was passing in a flag with the URL entrypoint (in our case: this is a Teams Tab) https://<oururl>?context=teams and only using the Teams codepath when in Teams.
I have seen requests in the Microsoft Teams .js github to return a failure from the microsoftTeams.getContext(...) refer: is there any API to detect running in Teams or not?
Prior to the flag, I had some Typescript code that looks like
WireTeams(): Promise<boolean> {
this._hasAttemptedConnection = false
return new Promise<boolean>((resolve, reject) => {
microsoftTeams.initialize()
microsoftTeams.getContext((context) => {
if (context === null || context === undefined) {
resolve(false)
}
this._teamsContext = context
})
})
this._hasAttemptedConnection = true
}
As of 2022, Microsoft released version 2.0 of teams-js library. You can check https://www.npmjs.com/package/#microsoft/teams-js. You can now use the app module to check whether it is initialized.
import { app } from '#microsoft/teams-js';
bool initialized = app.isInitialized()
Our application uses SignalR and we have enabled the websockets in our applicaiton. Sometimes we are getting the below error in browser console window and during the same time the auto update is not working. After the relaunch it is started working.
Firefox:
"The connection to ws://xx.xx.xx.xx:xxxxx/signalr/connect?transport=webSockets&connectionToken=%2F54BwG4ui3MbJPK2t8DfS9AklLCtAEDQ1sHeAsZ6e3h2LVT0WYbbgGvCI2AlnsJf0AqY4AzMtp6FS0xl07td8kKFYhAmIEL4GjLCXP%2Bhlfy3k226j%2B4fXHVB8Vvblewc&connectionData=%5B%7B%22name%22%3A%22pushdatahub%22%7D%5D&tid=7 was interrupted while the page was loading."
Chrome:
jquery.signalR-1.0.0.min.js:10 WebSocket is already in CLOSING or CLOSED state.
Please refer below setup done on the server.
.Net framework 4.6.1 in the server.
websockets enabled in IIS/Application
httpruntime set in web.config
Server uses SignalR Hub
Sample client code:
$scope.isHubConnectionFailed = false;
$scope.connection = $.hubConnection(AppURL);
$scope.HubProxy = $scope.connection.createHubProxy(App.chatHub);
$scope.connection.start()
.done(function () {
$scope.isHubConnectionFailed = false;
})
.fail(function() {
$scope.isHubConnectionFailed = true;
});
var tryingToReconnect = false;
$scope.connection.reconnecting(function() {
tryingToReconnect = true;
});
$scope.connection.reconnected(function() {
tryingToReconnect = false;
$scope.isHubConnectionFailed = false;
});
$scope.connection.disconnected(function() {
if (tryingToReconnect) {
$scope.isHubConnectionFailed = true;
}
});
Anyone having the same issue?
Check the version of the browser your using.
Supported Platforms: http://www.asp.net/signalr/overview/getting-started/supported-platforms
There is an issue I found with signalr and azure, I am not sure if that is your situation but it might help to debug the issue. https://github.com/SignalR/SignalR/issues/2780
I am trying to use push notifications on the iphone emulator, but I am not having any success, I am using the example code:
var deviceToken = null;
// Check if the device is running iOS 8 or later
if (Ti.Platform.name == "iPhone OS" && parseInt(Ti.Platform.version.split(".")[0]) >= 8) {
Ti.API.log("identificada versão 8");
// Wait for user settings to be registered before registering for push notifications
Ti.App.iOS.addEventListener('usernotificationsettings', function registerForPush() {
Ti.API.log("Notifications config set");
// Remove event listener once registered for push notifications
Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
Ti.Network.registerForPushNotifications({
types : [Ti.App.iOS.NOTIFICATION_TYPE_BADGE, Ti.App.iOS.NOTIFICATION_TYPE_ALERT, Ti.App.iOS.NOTIFICATION_TYPE_SOUND],
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
});
// Register notification types to use
Ti.App.iOS.registerUserNotificationSettings({
types: [
Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT,
Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND,
Ti.App.iOS.USER_NOTIFICATION_TYPE_BADGE
]
});
}
// For iOS 7 and earlier
else {
Ti.Network.registerForPushNotifications({
// Specifies which notifications to receive
types: [
Ti.Network.NOTIFICATION_TYPE_BADGE,
Ti.Network.NOTIFICATION_TYPE_ALERT,
Ti.Network.NOTIFICATION_TYPE_SOUND
],
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
}
// Process incoming push notifications
function receivePush(e) {
alert('Received push: ' + JSON.stringify(e));
}
// Save the device token for subsequent API calls
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
subscribeToChannel();
}
function deviceTokenError(e) {
alert('Failed to register for push notifications! ' + e.error);
}
and none of the registerForPushNotifications() callbacks are being fired, the success, the error, or the callback are not being called, and I am having a hard time solving it, I searched a bit on the web, the solutions where:
to turn off the liveView, but it did not solve my problem,
testing on a real iphone didn't help;
Check all the pushnotifications configurations on the appcelerator dashboard, and everything was fine.
I still can't find a solution.
Push notification only works on device.Push Notifications iOS simulator
Configuring push services for iOS devices
As suggested by Jagu and Danny, there is no way to test the Push Notifications on simulator/emulator.
But also remember to turn off LIVE VIEW when you test it on physical device, otherwise you may not get device token.
I'm using service worker for push notifications, following this article. Everything is working with Chrome but with Firefox (v.44.0.2) I have a weird issue.
On successful login to my app, I register the service worker which does nothing but waiting for push events; I see that is correctly registered (from some logging and from about:serviceworkers). Now, if I refresh the page (CTRL+R) all my POST have CORS issues (missing Access-Control-Allow-Origin header) due to this service worker and the user is redirected to login page; from here on all POSTs do not work for the same reason.
Conversely, if I login, unregister the service worker and then refresh, there are no problems at all. Any idea of what's going on? Again my service worker just handles push events, no caching no other processing done and it perfectly works on Chrome.
Here's my service worker code ( SOME_API_URL points to a real API which is not needed for testing purpose cause the issue happens after the service worker registers, no push events needed)
self.addEventListener('push', function(event) {
// Since there is no payload data with the first version
// of push messages, we'll grab some data from
// an API and use it to populate a notification
event.waitUntil(
fetch(SOME_API_URL).then(function(response) {
if (response.status !== 200) {
// Either show a message to the user explaining the error
// or enter a generic message and handle the
// onnotificationclick event to direct the user to a web page
console.log('Looks like there was a problem. Status Code: ' + response.status);
throw new Error();
}
// Examine the text in the response
return response.json().then(function(data) {
if (data.error || !data.notification) {
console.error('The API returned an error.', data.error);
throw new Error();
}
var title = data.notification.title;
var message = data.notification.message;
var icon = data.notification.icon;
var notificationTag = data.notification.tag;
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
});
}).catch(function(err) {
console.error('Unable to retrieve data', err);
var title = 'An error occurred';
var message = 'We were unable to get the information for this push message';
var notificationTag = 'notification-error';
return self.registration.showNotification(title, {
body: message,
tag: notificationTag
});
})
);
});
self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
// Android doesn't close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients.matchAll({
type: 'window'
})
.then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow) {
return clients.openWindow('/');
}
})
);
});
Firefox 44 has bug 1243453, which causes the Origin header of cross-origin requests to get dropped if the service worker doesn't listen for fetch events.
The bug has been fixed in Firefox 45, which will be released the week of March 8, 2016 (next week, as of the time of this writing). In the meantime, and for users who don't immediately upgrade to the latest Firefox release, you can work around the problem by adding this code to the service worker:
addEventListener('fetch', function(evt) {
evt.respondWith(fetch(evt.request));
});