Electron with node-notifier display windows 10 notification - node.js

I'm trying to make a simple app that should display notification when button is clicked. The problem is that the notification does not show, but console.logs are showing. Should the notification work on development mode? (meaning just running electron ., and I don't have to build and install the app)
Windows OS:
Edition: Windows 10 Home
Version: 1709
Build:16299.98
NOTE: Toast is enabled (banner, action center) under System->Notification & Actions
Code:
// main.js
const { app, BrowserWindow, ipcMain, Notification } = require("electron");
const path = require("path");
const url = require("url");
let win;
function createWindow() {
// Create the browser window.
win = new BrowserWindow({ width: 800, height: 600 });
// and load the index.html of the app.
win.loadURL(
url.format({
pathname: path.join(__dirname, "index.html"),
protocol: "file:",
slashes: true
})
);
// Open the DevTools.
// win.webContents.openDevTools()
// Emitted when the window is closed.
win.on("closed", () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null;
});
}
const appId = "elite-notifier";
app.setAppUserModelId(appId);
app.on("ready", createWindow);
console.log("notifying");
ipcMain.on("notify", () => {
console.log("notified");
const WindowsToaster = require("node-notifier").WindowsToaster;
const notifier = new WindowsToaster({
withFallback: false
});
notifier.notify(
{
title: "My awesome title",
message: "Hello from node, Mr. User!",
sound: true, // Only Notification Center or Windows Toasters
wait: false // Wait with callback, until user action is taken against notification
},
function(err, response) {
// Response is response from notification
console.log("responded...");
}
);
});
// index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>Notifier!</h1>
<button type="button" id="notify">Click here to trigger a notification!</button>
<script type="text/javascript">
const { ipcRenderer } = require('electron');
const button = document.getElementById('notify');
console.log('BUTTON: ', button)
button.addEventListener('click', function(event) {
console.log('clicked...');
ipcRenderer.send('notify')
});
</script>
</body>
</html>

I've got it working now, thanks to all the people here :) https://github.com/mikaelbr/node-notifier/issues/144#issuecomment-319324058
Based on anthonyraymond's comment, you need to have your app INSTALLED in your windows machine with an appId. You can configure appId in your package.json like this.
{
"name": "myapp",
"version": "1.0.0",
"description": "test",
"main": "main.js",
"build": {
"appId": "com.myapp.id"
}
}
The appId does not need to have that java/android format, my app just have an appId of elite-notifier.
Then you can pass the appId when calling the notify function of notifier.
notifier.notify(
{
appName: "com.myapp.id", <-- yes, the key here is appName :)
title: "Hello",
message: "Hello world!",
wait: true
},
function(err, response) {
// Response is response from notification
console.log("responded...");
}
);
After installation, This will work even on development mode (by running electron . command) provided that you'll not change the appId of your app after installation since there will be a mismatch on the installed one and the development version of the app.

You don't need to use IPC and send notifications from the main process, this is supported from the renderer process using the HTML5 notification API.
let myNotification = new Notification('Title', {
body: 'Lorem Ipsum Dolor Sit Amet'
})
myNotification.onclick = () => {
console.log('Notification clicked')
}

I've also tried many things, but sometimes it works or not.
At last, I've found a way. This works well for not only "npm run dev", but also package built.
use Notification at renderer process.
register app id at package.json
"build": {
"appId": "my app id",
...
call app.setAppUserModelId("my app id") at main process (https://electronjs.org/docs/api/app#appsetappusermodelidid-windows)
Here app id can be any type of string.

This error doesn't need any configuration all you have to do is go to your setting and enable notification Because in some cases on your computer you just switched off notifications.
System Setting ->Notification & Actions
Then turn on Notification By clicking the switch (problem solved)

You can do this, it works for me even on windows 10.
in package.json
"build": {
"appId": "your.custom.app.id",
}
in main.js
app.setAppUserModelId("your.custom.app.id");

Related

Handle searching in Chrome extension panel

I have a custom Chrome dev tools extension panel which I want to search in. The panel and search are setup by this code (in devtools.js).
chrome.devtools.panels.create("SF Assist", "assets/logo64.png", "panel.html", function (panel) {
panel.onSearch.addListener(function (event) {
alert('search');
});
});
This loads panel.html, the html loads panel.js which builds the content of the tab. Panel.js communicates with the inspected tab and pulls a lot of information back. The code above hooks the onSearch event when a user does a search in the dev panel. The data is in panel.js but the hook is above. How do I communicate from this code to my panel.js?
As mentioned in the comments, communication between devtools.js and panel.js is via messaging. Needed to add messaging to devtools, panel.js already had the listener setup for communicating to the background script.
devtools.js
chrome.devtools.panels.create("SF Assist", "assets/logo64.png", "panel.html", function (panel) {
chrome.runtime.onConnect.addListener(function (port) {
console.log('dev tools connect listener', port);
var extensionListener = function (message, sender, sendResponse) {
console.log('dev tools listener received message', message, port);
}
port.onMessage.addListener(extensionListener);
var searchPanel = function (event, queryString) {
console.log('dev tools search', event, queryString);
port.postMessage(...);
}
panel.onSearch.addListener(searchPanel);
});
});

{Action name} isn't responding right now. Try again soon

I'm new with the ActionSDK and I created an project with the Action SDK.
The fulfillment of my actions is deploy in Azure as a web service.
I've being updating my action with:
gactions update --action_package action.json --project "projectID"
this being said, the update is successful.
this is my action.json:
{
"actions": [
{
"name": "MAIN",
"intent": {
"name": "actions.intent.MAIN",
"trigger": {
"queryPatterns": [
"talk to Conduent Helper",
"Talk to conduent help"
]
}
},
"fulfillment": {
"conversationName": "conduentHelpTest"
}
}
],
"conversations": {
"conduentHelpApp": {
"name": "conduentHelpTest",
"url": "https://dialogflowappnc.azurewebsites.net",
"fulfillmentApiVersion": 2
}
}
}
this is a fulfillment code I found after trying my own and had no success with it:
'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var exps = express();
const ApiAiApp = require('actions-on-google').ApiAiApp;
exps.use(bodyParser.json());
// API.AI actions
const WELCOME_ACTION = 'input.welcome';
exps.post('/', function(request, response) {
console.log("hello World");
const app = new ApiAiApp({request, response});
function greetUser (app) {
app.tell("Hello World!");
}
let actionMap = new Map();
actionMap.set(WELCOME_ACTION, greetUser);
app.handleRequest(actionMap);
});
exps.listen((process.env.PORT || 7001), function() {
console.log("App up and running, listening.")
})
Whenever I test in the simulator the response is:
{Action name} isn't responding right now. Try again soon.
Whenever I do an update with the command above I see in my web service a request. But when I try to test the action in the simulator I see no request being made.
If someone can point me in the right direction. Point out any knowledge I most gain before proceeding. I there's more info I need to provide let me know and thanks.
Sorry I do not have enough points to comment but We are currently experiencing an outage you can see here if you are being impacted https://azure.microsoft.com/en-us/status/
You will want to monitor the Azure Status Page for further updates. Unfortunately we cannot do anything until the problem has been mitigated by engineering.
There are a couple of potential issues:
First - you haven't shown your package.json file, but the code suggests you're using an older version of the actions-on-google library. So the code itself may not be running. Check your runtime logs to make sure it is.
Next, you've specified that it should be listening on port 7001, but the URL you've provided in the actions.json file doesn't include the port number. If that is the host and port it is running on, and you haven't provided a proxy of some sort, then you need to specify the URL as https://dialogflowappnc.azurewebsites.net:7001/
Also, if you're running on port 7001, you likely haven't opened up the firewall to access it.
But it seems likely you're running a proxy (or you should), since you also need to be providing a valid HTTPS connection with a valid SSL certificate. If this is a self-signed certificate, the connection may still be rejected.

Messenger Extensions object only has {"AppleMusic":{}}

I'm trying to make a messenger bot and chat extension.
I set the home_url
whitelisted the URL
Loaded the SDK correctly
doing everything inside window.extAsyncInit
And all the tests I'm doing are inside the messenger app in mobile.
But when I open the chat extension normally inside a chat thread and try to use,
getContext() or any other method
Nothing happens.
i.e.
<script type="text/javascript">
window.extAsyncInit = function () {
MessengerExtensions.getContext('I pasted my app id here without quotes',
function success(result){
alert("Success: "+result.psid);
},
function error(result){
alert(JSON.stringify(result));
}
);
};
</script>
and when I try to do this,
alert(JSON.stringify(MessengerExtensions))
it shows
{"AppleMusic":{}}
what am I missing?

azure node.js console.log not logging into stdout or stderr files

I have a node.js app in azure (app service). The node.js is using the following modules
"scripts": {
"start": "node bin\/www",
"test": "mocha"
},
"dependencies": {
"async": "^1.5.2",
"bluebird": "^3.3.4",
"express": "^4.13.3",
"ioredis": "^1.15.1",
"lodash": "^4.6.1",
"socket.io": "^1.4.5"
},
"devDependencies": {
"chai": "^3.5.0",
"socket.io-client": "^1.4.5"
}
I wanted to enable the logging of app so i set the environment variable DEBUG = * using the portal->configure->app settings. since then, the app's express and socketio logs started to appear in /LogFiles/Application folder with cryptic name xxxxxx-nnnn-stderr-nnnnnnnnnnnnnn.txt
I added a console.log statement in one of the files in my app's lib folder
function MessageActions(redis, io) {
...
}
MessageActions.prototype.routeMessage = function(message) {
console.log('routeMessage: ' + JSON.stringify(message)); //this is not appearing anywhere in logs
var self = this;
return Promise.join(
self.checkUserMessage(message),
self.checkGroupMessage(message),
function(sendtarget, sendgroup) {
if(!sendtarget && !sendgroup) {
var pmsg = util.inspect(message);
throw new Error('Failed to route message: ' + pmsg);
}
}
);
}
I am sure that this function is being called as i could see the below error in the stderr file
[Error: Failed to route message: { ... }]
But i am not able to find the log statement added with console.log anywhere in this stderr file. also, there is no stdout file in the /LogFiles/Application folder.
How to add a log statement and where to check for it?
My IISNode.yml file has the following two lines
loggingEnabled: true
devErrorsEnabled: true
Please try to set the Application Logging (Filesystem) to on to enable the streaming log feature.
After that, you will find several logs files in /LogFiles/Application folder with cryptic name xxxxxx-nnnn-stdout-nnnnnnnnnnnnnn.txt which contain the output of your console.log().
But please notice the description:
Enable application logging to collect diagnostic traces from your web app code. You'll need to turn this on to enable the streaming log feature. This setting turns itself off after 12 hours.
To keep a persistence logging files in Node.js applications, you can use some node.js logging libraries like winston.
There is a way to see the console output live if you take the following steps:
Open website blade in Azure portal
Click on the tools icon
Click on the "Visual Studio Online" tool
Toggle the tool to "On"
...wait while the extension is enabled
Click the "Go->" icon under the tool toggle.
Once Visual Studio Online "Monaco" window is up, you can "Run" your application which should show your website in another window, but your "Monaco" window will have the console output from your application.
Hope this helps find your problem.
In your Index.js/Messages , replace the following code:
if (useEmulator) {
var restify = require('restify');
var server = restify.createServer();
server.listen(3978, function() {
console.log('test bot endpoint at http://localhost:3978/api/messages');
});
server.post('/api/messages', connector.listen());
}
else {
module.exports = { default: connector.listen() }
}
with:
if (useEmulator) {
var restify = require('restify');
var server = restify.createServer();
server.listen(3978, function() {
console.log('test bot endpoint at http://localhost:3978/api/messages');
});
server.post('/api/messages', connector.listen());
}
else {
var listener = connector.listen();
var withLogging = function(context, req) {
console.log = context.log;
listener(context, req);
}
module.exports = { default: withLogging }
}
This will override the console.log function. Hope , this will help.

phonegap webos 3.0+

I have a phonegap iOS app that i ported to webos on the touchpad the app works great except for the one iOS plugin that i used. it basically saved the canvas data to the photo roll. From my understanding of webos i will need to create a node.js service and write the data to a buffer and finally to the file system, there is an example for that in the forums. however what i can not figure out is how to call all of this from my phonegap app. I believe i will need to have the following in my index.html file.
<script src="/opt/PalmSDK/Current/share/framework/enyo/1.0/framework/enyo.js" type="text/javascript"></script>
and something like
enyo.create({kind: "Main"}).renderInto(document.body);
my guess i will also have to have all of the "kind" data in a js file. but how do i do the little step from my app's js file to communicate with the service that is created. I looked in the phonegap 1.0.js file and see that they are calling services this way.
this.service = navigator.service.Request('palm://com.palm.applicationManager', {
method: 'launch',
parameters: {
id: 'com.palm.app.camera',
params: {
appId: 'com.palm.app.camera',
name: 'capture',
sublaunch: true,
filename: filename
}
},
onSuccess: successCallback,
onFailure: errorCallback
});
but i also noticed it appears that it is all mojo and what i am doing is enyo, so yes i am pretty confused the moment...
seems it should be easy to call a service in webos, say here is a string of image data and write it to the file system from my existing phonegap app. and not have to do everything in enyo. anyone have a sample of a webos plugin like this or know where to point me?
thanks tim
**Update
I have created a node service now as defined below, i think that works and i am trying to make the call to the service, but it does not get to it. the test app runs on my touchpad, but when i push the button to save the image i do not get into the service. I tried to follow what was done for the camera in the phonegap0.0.1.js file this is a copy of my service, how i defined it and how i am calling it. any ideas what i am doing wrong.
services.json =
"id": "com.tim.pgmojo1.service",
"description": "FileIO Service",
"services": [
{
"name": "com.tim.pgmojo1.service",
"description": "FileIO Service",
"commands": [
{
"name": "writefile",
"assistant": "WriteFileAssistant",
"public": true
}]
}]
}
** service code
var libraries = MojoLoader.require({ name: "foundations", version: "1.0" });
var fs = IMPORTS.require("fs");
var sys = require('sys');
var WriteFileAssistant = function() {}
WriteFileAssistant.prototype.run = function(future) {
var mypath = this.controller.args.thepath;
var mydata = this.controller.args.thedata;
console.log("in write file");
console.log("path=" + thepath);
console.log("image data=" + thedata);
var data = content.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile('/media/internal/downloads/timimage.png', buf);
}
my call to the service**
this.service = navigator.service.Request('palm://com.tim.pgmojo.service', {
method: 'writefile',
parameters: {
thepath: '/media/internal/downloads/timimage.png',
thedata: canvasData
},
onSuccess: mySuccess,
onFailure: myFailure
});
currently i have this in my index.html file since it is only for testing..
Mojo is still included on the TouchPad. You can use the same service-calling functions as PhoneGap is doing.
In Enyo, access to on-device services is handled by the enyo.PalmService kind. You can see an example of an app that has a node.js service included and how calls are made to this service at https://github.com/palm/txjs-fortunecookie

Resources