How to get app name from electron renderer? - electron

I'm using an Electron React boilerplate and I'm interested in getting the app name from inside one of my react component file.
I've tried this
import {app} from 'electron'
const name = app.getName()
but I get the error
hot update failed for module "./app/containers/Root.tsx". Last file processed: "./app/components/Modal/Text.tsx".
I'm guessing electron cannot be accessed from the "renderer"? what's the best way to access this data?

TLDR: Send a message to the main process and have it send back a message containing the app name.
You're correct that you can't get the app name from the renderer.
So I'd send a message to the main process requesting the app name, then have the main process send back the app name.
This is how the code would look:
renderer.js
var ipcRenderer = require('electron').ipcRenderer;
// Send message.
ipcRenderer.send('asynchronous-message', 'getAppName');
// Recieve app name.
ipcRenderer.on('asynchronous-message', function (evt, messageObj) {
console.log(messageObj); // This will contain the app name.
});
main.js
var ipcMain = require('electron').ipcMain;
var app = require('electron').app;
ipcMain.on('asynchronous-message', function (evt, messageObj) {
// Send message back to renderer.
if (messageObj == 'getAppName') {
evt.sender.webContents.send('asynchronous-message', app.getName());
}
});
Docs for ipcMain.
Docs for ipcRenderer.

Related

Add deep link when creating Firebase message

I'm using the firebase Message class to create push notifications for a react native app. I want the notification to take users to a specific screen of the app. Right now tapping on the push notification just takes users to the last screen they were on before they back-grounded the app. I'm testing this on my iOS device. How can I embed a specific deep link in the message? Would I use setApnsConfig(ApnsConfig apnsConfig) or setFcmOptions(FcmOptions fcmOptions)?
I would use the APNS config since this is for an iOS app:
https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/messaging/ApnsConfig.Builder
You could approach it different ways, but you could either include a URL in the header field, and use it for custom deep link logic, or you can have custom data in the putCustomData(String key, Object value) and then have your app process that info to deep link into the correct part of your app.
Your app would process this notification in the application(_:didReceiveRemoteNotification:fetchCompletionHandler:)
https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application
I had integrated this feature in an app I made in react native aswell. Look at my solution below.
As you can see in the app I am waiting for a notification to come on and I check if it has a type available. My notifications are always routed to another page. In my case its the same page but I set a route as datatype in my payload.
After that you can use that route payload with your naviogator library in my case react-navigation to navigate to the correct screen.
You should chose which trigger works best for you ether onNotificationOpenedApp or getInitialNotification.
useEffect(() => {
// Assume a message-notification contains a "type" property in the data payload of the screen to open
messaging().onNotificationOpenedApp((remoteMessage) => {
console.log(
"Notification caused app to open from background state:",
remoteMessage
);
//navigation.navigate(remoteMessage.data.type);
});
// Check whether an initial notification is available
messaging()
.getInitialNotification()
.then((remoteMessage) => {
if (remoteMessage) {
console.log(
"Notification caused app to open from quit state:",
remoteMessage
);
const route = remoteMessage?.data?.route;
navigation.navigate(route, {
data: remoteMessage.data,
});
}
})
.catch((error) => console.log("Caught ", error));
}, []);

How to differentiate two ipc renderer in one ipc main (same channel)

I want to detect the specific frame/browserWindow. I have one main process and two browser windows which all three are sending message to each other using same channel . in IPCMain I need to detect one of them. I saw that IPCmain event has a function named frameId but when I use it I get undefined.
ipcMain.once("postMessage", (event, message) => {
if(!activeRequest) return;
activeRequest.json(message).send();
});
You can the get the current webcontent id from the main process by accessing the sender object in the events object which is the first argument.
console.log(event.sender.webContents.id);
you can also pass the id of the window that the eent is coming from via the renderer process.
// in the renderer process do this
electron.ipcRenderer.send("new-message", {
winId: electron.remote.getCurrentWebContents().id ,
message: "Hi"
});
when the main process receives this event, you just have to access the winId property in the message object
Either you can pass the identity in ipc message payoad, or you can get the windows web content id via, ipc message's sender object.

How to show data changes locally before it updated and showed up in firestore

I'm following a tutorial for an chat app with flutter and firebase firestore. In that app when user sends a text message to other it's not visible to sender till it's get updated in firestore and then the new data is showing up in the messages list. I want to is it possible to add the newly sent message to the messages list with a clock image indicating that it will update in database and then after it's updated in database then locally added message should be replaced with data from firestore in messages list.
Here is snippet of button press to send message...
void onSendMessage(String content, int type) {
// type: 0 = text, 1 = image, 2 = sticker
if (content.trim() != '') {
textEditingController.clear();
var documentReference = Firestore.instance
.collection('messages')
.document(groupChatId)
.collection('message')
.document(DateTime.now().millisecondsSinceEpoch.toString());
Firestore.instance.runTransaction((transaction) async {
await transaction.set(
documentReference,
{
'idFrom': id,
'idTo': peerId,
'timestamp': DateTime.now().millisecondsSinceEpoch.toString(),
'content': content,
'type': type
},
);
});
listScrollController.animateTo(0.0,
duration: Duration(milliseconds: 300), curve: Curves.easeOut);
} else {
Fluttertoast.showToast(msg: 'Nothing to send');
}
}
and here is the link to the tutorial Chat app with flutter and firestore
This shouldn't be too difficult to achieve.
Currently any new chat message is sent to the Firestore database upon submission.
You just need to extend the onSubmit function that does it (it probably has another name in your code example) to also add the message temporarily to the local message list.
Once you receive the update from the database you just have to remove the temporary message from the list since it will be replaced with the contents from the database. Include the progress indicator with the temporary message and you're done.
If you need a more detailled answer please add some code to your question (ideally together with a link to the original tutorial. Note: When providing a link to an external page make sure that you question is still complete should the link go dead.)
I used a cloud function to achieve this. I have a field isSent on my message and it's initially false, when the message gets created in firestore, I then update the isSent field using the cloud function and that automatically rebuilds the UI. It's not very fast and accurate, but much better than none

Google Cloud Functions Notifications iOS

I was finishing up an app for somebody but needed some help with the script that I wrote for sending notifications via Cloud Functions for Firebase. Below this text you can find my code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/Users/{userUid}/').onWrite(event => {
const followerUid = event.params.userUid;
const payload = {
notification: {
title: 'Update Received',
body: 'Please Check Your App',
badge: 1,
sound: 1,
}
};
return admin.database().ref('/Admin/notificationID').once('value').then(allTokens => {
if (allTokens.val()) {
// Listing all tokens.
const tokens = allTokens.value
return admin.messaging().sendToDevice(tokens, payload).then(response => {
});
};
});
});
Mainly there are only 3 issues that I am having. First of all, I am not sure if I am using the correct syntax for specifying the badge. Second of all, I don't know how to specify that I want a sound to be played for the notification. Lastly, I am unable to send the notification because the notificationID that is returned from the database is apparently incorrect even though I have a legible FCM ID stored in my database under /Admin/ with the key notificationID. I would appreciate it if one of you could help me fix these issues and get this app up and running.
Thanks,
KPS
The value for badge needs to be String:
Optional, string
Same in #1, sound value needs to be String:
Optional, string
The sound to play when the device receives the notification.
Sound files can be in the main bundle of the client app or in the Library/Sounds folder of the app's data container. See the iOS Developer Library for more information.
Hard to tell without any additional details. Are you positive that it's a valid registration token? Does it work when you send a message to it using the Firebase Console? If not, is it throwing an error?

How to get key/value data from PushNotification in PhoneGap Build

I'm using the Push plugin in PhoneGap Build. I am able to send as well as receive push notifications to my device. I'm sending the notification + additional data (specifically which page to load) using the node-gcm library to registered devices. Here's the code on my node.js server:
var gcm = require('node-gcm');
var message = new gcm.Message();
//API Server Key
var sender = new gcm.Sender('GCM API SERVER/BROWSER KEY');
var registrationIds = [];
// Value the payload data to send...
message.addData('message','Hello from Portland, OR!');
message.addData('title','My Push Notification');
message.addData('msgcnt','3');
message.addData('soundname','beep.wav');
message.addDataWithKeyValue('pageid','1234566788'); //THIS IS THE ADDITIONAL DATA I'D
// ... ID LIKE TO SEND TO MY PHONEGAP BUILD APP AND INTERPRET
message.timeToLive = 3;// Duration in seconds to hold and retry to deliver the message in GCM before timing out. Default 4 weeks if not specified
// At least one reg id required
registrationIds.push('REGISTRATION ID');
/**
* Parameters: message-literal, registrationIds-array, No. of retries, callback-function
*/
sender.send(message, registrationIds, 4, function (result) {
console.log("hello" + result);
});
Now that I believe I have sent the additional page data, I'd like to know how I can GET the data from the notification itself inside of my PhoneGap build application.
I'm also using jquery mobile to manage the different html pages (which basically makes each page a separate div inside of one html document) and could use feedback on how to load the notified page with this in mind.
Any help would be greatly appreciated, thanks so much!
-- 24x7
You can get the value of key/pairs of notification in phonegap as follows:
The message text can be retrieved with: e.message
All other key/value pairs can be retrieved with: e.payload.key
For example if you want get the title of the notification(in above) then you will get it in "e.payload.title".
After getting the value you can put conditional statemnets depending upon the value to go to different pages/divs.

Resources