Using firebase-messaging.js v8.2.0 and using onBackgroundMessage to show notification, the notification is being sent 2 times, the default one and the onBackgroundMessage one.
What are your thoughts abou this problem? Code is same as documented in the firebase mesaging quickstart sample
I changed one of firebase notification scripts code. There was an unexpected bug which is sending the notification two times. I can send you the files. Meanwhile, this is my firebase-messaging.sw.js (I hided the keys).
importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js");
importScripts("firebase-messaging.js");
/*
Initialize the Firebase app in the service worker by passing in the messagingSenderId.
* New configuration for app#pulseservice.com
*/
firebase.initializeApp({
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log("[firebase-messaging-sw.js] Received background message ", payload);
// Customize notification here
let url = payload.data.notification_url;
const notificationTitle1 = payload.notification.title;
const notificationOptions1 = {
body: payload.notification.body,
icon: "",
data: { url: payload.data.notification_url },
image: payload.notification.image
};
return self.registration.showNotification(notificationTitle1, notificationOptions1);
});
self.addEventListener("notificationclick", function (event) {
let url = event.notification.data.url;
event.notification.close();
event.waitUntil(
clients.matchAll({ type: "window" }).then(windowClients => {
// Check if there is already a window/tab open with the target URL
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
// If so, just focus it.
if (client.url === url && "focus" in client) {
return client.focus();
}
}
// If not, then open the target URL in a new window/tab.
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
The file I changed is firebase-messaging.js and saved it into the sites static files with the changes I made. Let me know if you need it.
Related
I've implemented the agora sdk 3.0 for video calls.
now I'm trying to get screen sharing to work, but I keep getting the error provided in
the picture below (Join failed: NO_AUTHORIZED).
Picture of console while sharing a screen
screen sharing code sample:
async shareScreen() {
this.shareClient = AgoraRTC.createClient({
mode: 'rtc',
codec: 'vp8'
})
this.shareClient.init('xxxxxxxxxxxxxx', () => {
this.shareClient.join('same token video call started with', 'same room name of current outgoing video call', null, (uid) => {
const streamSpec = {
streamID: uid,
audio: false,
video: false,
screen: true
}
if (isFirefox()) {
streamSpec.mediaSource = 'window';
} else if (!isCompatibleChrome()) {
streamSpec.extensionId = 'minllpmhdgpndnkomcoccfekfegnlikg';
}
this.shareScreenStream = AgoraRTC.createStream(streamSpec);
// Initialize the stream.
this.shareScreenStream.init(() => {
// Play the stream.
this.shareScreenStream.play('renderer');
// Publish the stream.
this.shareClient.publish(this.shareScreenStream);
}, function(err) {
console.log(err);
});
}, function(err) {
console.log(err);
})
});
},
The screensharing client should use an unique token based on the UID and channel name. Not the one the main user is using.
I am trying to follow the guide here ( https://stripe.com/docs/stripe-js/elements/payment-request-button ) to setup Apple Pay for the web and Stripe. The initial steps such as verification of domain and all the pre-setup is done but I am having an issue following the steps for the payment.
The Apple Pay Button is showing up in my Safari browser. When the button is clicked, I fire an event called Paymentmethode() i am facing this error while checking live.Either you do not have a card saved to your Wallet or the current domain (pwafe.devco.pk) is not registered for Apple Pay. Visit https://dashboard.stripe.com/account/apple_pay to register this domain.
main.js:25. and button is hide I get lost after step 3 and not sure what to do. I am posting to my backend and on the backend, creating a payment intent and returning the client_secret
paymentMethod() {
// STEP 1 FROM GUIDE
var stripe = Stripe("pk_test_YxSI6F4QeV0XCofSgabilbTu00ChOmJWJ0", {
apiVersion: "2020-08-27",
stripeAccount: "CONNECTED_STRIPE_ACCOUNT_ID",
});
// STEP 2 FROM GUIDE
var paymentRequest = stripe.paymentRequest({
country: "US",
currency: "usd",
total: {
label: "Demo total",
amount: 1099,
},
requestPayerName: true,
requestPayerEmail: true,
});
// STEP 3 FROM GUIDE
var elements = stripe.elements();
var prButton = elements.create("paymentRequestButton", {
paymentRequest: paymentRequest,
});
// console.log("before api call", paymentRequest);
paymentRequest.canMakePayment().then(function (result) {
// console.log("after api called" + result);
if (result) {
prButton.mount("#payment-request-button");
} else {
//prButton.mount('#payment-request-button');
document.getElementById("payment-request-button").style.display =
"none";
}
});
// STEP 4 FROM GUIDE -- THIS RETURNS A CLIENT SECRET
let clientSecret;
axios
.post("https://pwa.devco.pk/api/Create_PaymentIntent", {})
.then((resp) => {
// Assign this previously defined variable
clientSecret = resp.client_secret;
});
paymentRequest.on("paymentmethod", function (ev) {
// Confirm the PaymentIntent without handling potential next actions (yet).
stripe
.confirmCardPayment(
clientSecret,
{
payment_method: ev.paymentMethod.id,
},
{
handleActions: false,
}
)
.then(function (confirmResult) {
if (confirmResult.error) {
// Report to the browser that the payment failed, prompting it to
// re-show the payment interface, or show an error message and close
// the payment interface.
ev.complete("fail");
} else {
// Report to the browser that the confirmation was successful, prompting
// it to close the browser payment method collection interface.
ev.complete("success");
// Check if the PaymentIntent requires any actions and if so let Stripe.js
// handle the flow. If using an API version older than "2019-02-11" instead
// instead check for: `paymentIntent.status === "requires_source_action"`.
if (confirmResult.paymentIntent.status === "requires_action") {
// Let Stripe.js handle the rest of the payment flow.
stripe.confirmCardPayment(clientSecret).then(function (result) {
if (result.error) {
let data = {
msg: "An error occurred. Please try again.",
};
this.handleShowFlashMsg(data);
// The payment failed -- ask your customer for a new payment method.
} else {
this.handleShowOrderConfirmModal();
// The payment has succeeded.
}
});
} else {
// The payment has succeeded.
}
}
});
});
var paymentRequest = stripe.paymentRequest({
country: "US",
currency: "usd",
total: {
label: "Demo total",
amount: 1099,
},
requestShipping: true,
// `shippingOptions` is optional at this point:
shippingOptions: [
// The first shipping option in this list appears as the default
// option in the browser payment interface.
{
id: "free-shipping",
label: "Free shipping",
detail: "Arrives in 5 to 7 days",
amount: 0,
},
],
});
paymentRequest.on("shippingaddresschange", function (ev) {
if (ev.shippingAddress.country !== "US") {
ev.updateWith({
status: "invalid_shipping_address",
});
} else {
// Perform server-side request to fetch shipping options
fetch("/calculateShipping", {
data: JSON.stringify({
shippingAddress: ev.shippingAddress,
}),
})
.then(function (response) {
return response.json();
})
.then(function (result) {
ev.updateWith({
status: "success",
shippingOptions: result.supportedShippingOptions,
});
});
}
});
var stripe = Stripe("pk_test_YxSI6F4QeV0XCofSgabilbTu00ChOmJWJ0", {
apiVersion: "2020-08-27",
stripeAccount: "CONNECTED_STRIPE_ACCOUNT_ID",
});
},
You should verify domain registration and add card into wallet.tha
I am trying to send push notifications using react-native-firebase through firebase console when my app is closed or in the background, the notifications are received and shown as a pop-up but if my app is in the foreground the notifications are not appearing
I have been trying to do some code in on notification method as suggested in the docs but it's not working
please suggest something that my app can show notifications in foreground
Please refer following link.
https://rnfirebase.io/docs/v5.x.x/messaging/android#(Optional)-Background-Messages
If you added, remove following line from your AndroidManifest.xml.
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
create a new notifactionHandler.js and import the code below.
import firebase from 'react-native-firebase';
exports.setNotificationListener = () => {
return new Promise((resolve, reject) => {
// triggers when notifiaction received while app on foreground
this.notificationListener = firebase.notifications().onNotification((notification) => {
console.log(notification.data);
setNotification({notification})
});
resolve(true);
})
};
const setNotification = ({notification}) => {
firebase.notifications().displayNotification(notification);
}
then import it on your splash or main page.
then call setNotificationListener function. basicly firebase.notifications().onNotification catches notifications while app on foreground, and displays it with firebase.notifications().displayNotification
in my case:
import firebase from 'firebase';
import * as Notice from "react-native-firebase";
componentDidMount() {
const firebaseConfig = {
apiKey: "**********",
authDomain: "**********",
databaseURL: "**********",
projectId: "**********",
storageBucket: "**********",
messagingSenderId: "**********",
appId: "**********"
};
this.mNotifiConfig()
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
}
mNotifiConfig = async() => {
Notice.messaging().hasPermission()
.then(enabled => {
console.log('HAS PERMISS: ', enabled)
if (enabled) {
Notice.messaging().getToken().then(token => {
console.log("LOG: ", token);
}).catch(err=> console.log(err))
} else {
Notice.messaging().requestPermission()
}
});
const notificationOpen = await Notice
.notifications()
.getInitialNotification();
if (notificationOpen) {
const action = notificationOpen.action;
const notification = notificationOpen.notification;
var seen = [];
// this.onActionWithNotification(notification)
console.log('NOTIFICATION IS OPNE')
}
// config android
const channel = new Notice.notifications.Android.Channel(
"test-channel",
"Test Channel",
Notice.notifications.Android.Importance.Max
).setDescription("My apps test channel");
// Create the channel
Notice.notifications().android.createChannel(channel);
this.notificationDisplayedListener = Notice
.notifications()
.onNotificationDisplayed((notification: Notification) => {
console.log('CREATED CHANNEL')
// Process your notification as required
// ANDROID: Remote notifications do not contain the channel ID. You will have to specify this manually if you'd like to re-display the notification.
});
this.notificationListener = Notice
.notifications()
.onNotification((notification: Notification) => {
console.log('HAS Notification: ', notification)
// Process your notification as required
// notification.android
// .setChannelId("test-channel")
// .android.setSmallIcon("ic_launcher");
// firebase.notifications().displayNotification(notification).catch(err => console.error(err));
let notification_to_be_displayed = new Notice.notifications.Notification({
data: notification.data,
sound: 'default',
show_in_foreground: true,
title: notification.title,
body: notification.body,
});
if(Platform.OS == "android") {
notification_to_be_displayed
.android.setPriority(Notice.notifications.Android.Priority.High)
.android.setChannelId("test-channel")
.android.setSmallIcon("ic_launcher")
.android.setVibrate(1000);
}
Notice.notifications().displayNotification(notification_to_be_displayed);
});
this.notificationOpenedListener = Notice
.notifications()
.onNotificationOpened((notificationOpen) => {
// Get the action triggered by the notification being opened
const action = notificationOpen.action;
// Get information about the notification that was opened
const notification = notificationOpen.notification;
var seen = [];
console.log('notification Day nay', notification)
Notice
.notifications()
.removeDeliveredNotification(notification.notificationId);
// this.onLinkingtoApp()
});
this.onMessageListener = Notice.messaging().onMessage((message: RemoteMessage) => {
const {data} = message
const showNotif = new Notice.notifications.Notification()
.setNotificationId('notificationId')
.setTitle(data.title || 'Thông báo')
.setBody(data.content || 'Bạn có một thông báo mới')
.setData(data)
.android.setChannelId('test-channel')
.android.setSmallIcon('ic_launcher')
Notice.notifications().displayNotification(showNotif)
})
}
I am trying to download an image from url then share it via whats app and other social media as an image format, I tried some method but I couldn't, my code is as follow:
let filePath = null;
const configOptions = {
fileCache: true,
};
RNFetchBlob.config(configOptions)
.fetch('GET', url)
.then(async resp => {
filePath = resp.path();
let options = {
url: filePath
};
await Share.open(options);
await RNFS.unlink(filePath);
});
I tried also
RNFetchBlob.fetch("GET",url,{
Authorization : 'Bearer access-token...',
})
.then(resp => {
console.log(resp)
let shareImageBase64 = {
title: "React Native",
message: "Hola mundo",
url: `data:image/png;base64,` + resp.base64(),
};
Share.open(shareImageBase64);
})
it does open the share option but there is no image, only the message can be shared.
This is an open issue in github, the issue is only on IOS when sharing with whats app. The problem is that the message under shareImageBase64 overrides the url and you are sharing the message only, a workaround is to remove the message and you will be able to share your image successfully.
In my grails 2.3.7 application,
I am using atmosphere-meteor 0.8.3.
On my home page load, I subscribe the client. And by default I run long-polling; and it works fine.
On page refresh, I unsubscribe the client.
However, if I refresh the page; then some of the JS and CSS fails to load. It happens 5 out of 10 times of refresh.
Am I doing anything wrong? (As I subscribe on document.ready()).
Or do I need to do anything else?
Any help is appreciated.
Update:
Code inside gsp for subscription:
$('body').bind('beforeunload',function(){
Jabber.unsubscribe();
});
$(document).ready(function () {
if (typeof atmosphere == 'undefined') {
Jabber.socket = $.atmosphere;
} else {
Jabber.socket = atmosphere;
}
var atmosphereRequest = {
type: 'public',
url: 'atmosphere/public',
trackMessageLength: false
};
//setTimeout(function(){
Jabber.subscribe(atmosphereRequest);
//}, 10000);
});
And the Jabber variable
var Jabber = {
socket: null,
publicSubscription: null,
transport: null,
subscribe: function (options) {
var defaults = {
type: '',
contentType: "application/json",
shared: false,
//transport: 'websocket',
transport: 'long-polling',
fallbackTransport: 'long-polling',
trackMessageLength: true
},
atmosphereRequest = $.extend({}, defaults, options);
console.log(atmosphereRequest);
atmosphereRequest.onOpen = function (response) {
console.log('atmosphereOpen transport: ' + response.transport);
};
atmosphereRequest.onReconnect = function (request, response) {
console.log("atmosphereReconnect");
};
atmosphereRequest.onMessage = function (response) {
console.log("on message");
Jabber.onMessage(response);
};
atmosphereRequest.onError = function (response) {
console.log('atmosphereError: ' + response);
};
atmosphereRequest.onTransportFailure = function (errorMsg, request) {
console.log('atmosphereTransportFailure: ' + errorMsg);
};
atmosphereRequest.onClose = function (response) {
console.log('atmosphereClose: ' + response);
};
switch (options.type) {
case 'public':
Jabber.publicSubscription = Jabber.socket.subscribe(atmosphereRequest);
break;
default:
return false;
}
//Jabber.publicSubscription = Jabber.socket.subscribe(atmosphereRequest);
},
unsubscribe: function () {
if (Jabber.socket)
Jabber.socket.unsubscribe();
},
onMessage:function(response){....}
}
I'm the plugin author. Please update to version 1.0.1. If you still have trouble after updating the plugin, create a new issue. We can work through the problem then. However, I do have a question. When you say the JS fails to load, do you mean the atmosphere JavaScript or your own? There is no plugin related CSS.