Giter VIP home page Giter VIP logo

electron-notify's Introduction

electron-notify

Nice and simple notifications for electron apps

Mac demo Win demo

electron-notify displays notifications in the lower right corner. Notifications are stacked (most recent on the top) and slide down, once they expire. electron-notify is forked from nw-notify which displays notifications for nw.js apps.

Features

  • Windows and Mac supported (Linux not tested, but should work)
  • AppIcons (optional, left of notification text) and images (optional, right of notification text)
  • Sounds
  • Close button (top right corner)
  • Open URLs (optional)
  • Callbacks for show, click and close
  • Queues notifications if not all can be shown at once

Usage

var eNotify = require('electron-notify');
// Change config options
eNotify.setConfig({
    appIcon: path.join(__dirname, 'images/icon.png'),
    displayTime: 6000
});

// Send simple notification
eNotify.notify({ title: 'Notification title', text: 'Some text' });
// Notification with URL, click notification to open
eNotify.notify({ title: 'Notification title', text: 'Some text', url: 'http://wikipedia.org'});
// Or with image and playing a sound on show
eNotify.notify({
    title: 'Notification title',
    text: 'Some text', url: 'http://wikipedia.org',
    image: path.join(__dirname, 'images/image.png'),
    sound: path.join(__dirname, 'sound.wav')
});
// Do something when user clicks on notification
eNotify.notify({ title: 'Custom func', onClickFunc: function() {
    // Your code here
    console.log('User clicked notification')
}});

// Change config options between notify calls
eNotify.setConfig({
    appIcon: path.join(__dirname, 'images/otherIcon.png'),
    defaultStyleText: {
        color: '#FF0000',
        fontWeight: 'bold'
    }
});
// Send notification that uses the new options
eNotify.notify({ title: 'Notification title', text: 'This text is now bold and has the color red' });

// See below for more options

Function reference

notify(notificationObj)

Display new notification. For possible properties see example below:

notify({
    title: 'Title',
    text: 'Some text',
    image: 'path/to/image.png',
    url: 'http://google.de',
    sound: path.join(__dirname, 'notification.wav'),
    onClickFunc: function() { alert('onCLick') },
    onShowFunc: function() { alert('onShow') },
    onCloseFunc: function() { alert('onClose')}
});

For more info on the onClickFunc, onShowFunc and onCloseFunc callbacks see below.

setConfig(configObj)

Change some config options. Can be run multiple times, also between notify()-calls to change electron-notifys behaviour.

closeAll()

Clears the animation queue and closes all windows opened by electron-notify. Call this to clean up before quiting your app.

setTemplatePath(path)

If you want to use your own notification.html you use this method. Use it like this: eNotify.setTemplatePath(path.join(__dirname, 'path/to/notification.html'));

calcMaxVisibleNotification() : int

Returns the maximum amount of notifications that fit onto the users screen.

Max notifications and queueing

On startup electron-notify will determine the maximum amount of notifications that fit on the screen. This value will be stored in config.maxVisibleNotifications but cannot be greater than 7. This is to ensure that all animations go smoothly and electron-notify does not freeze your computer. However you can overwrite this value with setConfig(). If you do that you should use calcMaxVisibleNotification() to check if that many notifications fit onto the users screen. Queueing: Once the limit of config.maxVisibleNotifications is reached, electron-notify will queue all new notifications internally. The order of notifiy()-calls will be preserved and once old notifications fade out, the queued notifications are shown.

Callbacks

Calling notify() will return an unique id for this particular notification. Each callback (onClickFunc, onShowFunc, onCloseFunc) will return an event object which contains the notification id, the event name(click, show, close, timeout, closeByAPI) and a function to close the notification:

{
    id: 32,
    name: 'click',
    closeNotification: function() {}
}

Example

function handleClick(event) {
    console.log('User clicked notification ' + event.id + '. Closing it immediately.');
    event.closeNotification();
}

function handleClose(event) {
    console.log('Notification was closed because: ' + event.name);
}

eNotify.notify({
    title: 'Notification title',
    text: 'Some text',
    onClickFunc: handleClick,
    onCloseFunc: handleClose
});

Config options

Default config:

  {
    width: 300,
    height: 65,
    padding: 10,
    borderRadius: 5,
    displayTime: 5000,
    animationSteps: 5,
    animationStepMs: 5,
    animateInParallel: true,
    appIcon: null,
    pathToModule: '',
    logging: true,
    defaultStyleContainer: {
      backgroundColor: '#f0f0f0',
      overflow: 'hidden',
      padding: 8,
      border: '1px solid #CCC',
      fontFamily: 'Arial',
      fontSize: 12,
      position: 'relative',
      lineHeight: '15px'
    },
    defaultStyleAppIcon: {
      overflow: 'hidden',
      float: 'left',
      height: 40,
      width: 40,
      marginRight: 10,
    },
    defaultStyleImage: {
      overflow: 'hidden',
      float: 'right',
      height: 40,
      width: 40,
      marginLeft: 10,
    },
    defaultStyleClose: {
      position: 'absolute',
      top: 1,
      right: 3,
      fontSize: 11,
      color: '#CCC'
    },
    defaultStyleText: {
      margin: 0,
      overflow: 'hidden',
      cursor: 'default'
    },
    defaultWindow: {
      alwaysOnTop: true,
      skipTaskbar: true,
      resizable: false,
      show: false,
      frame: false,
      transparent: true,
      acceptFirstMouse: true
    }
  }

Changelog

0.1.0

0.1.0 - Initial version

License

The MIT License (MIT)

Copyright (c) 2016 Hank Bao <[email protected]> (https://github.com/hankbao)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

electron-notify's People

Contributors

colonelbundy avatar ghostfreak3000 avatar hankbao avatar jbeising avatar razzeee avatar sashazxtt avatar umweltschmutz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

electron-notify's Issues

margin of the text

Hello! Thanks a lot for making this wonderful little tool! It's really nice.

One question/request - is it possible to control the margin/padding of the title and body? I need to display an image on the left, but the text ends up touching it on the right and it would be great if I could offset the text a bit.
Thanks again!

win7和electron 1.6.6下报错了

win7和electron 1.6.6下报错了

C:\Users\Administrator\Desktop\demo\electron-notify-0.1.0>electron .

App threw an error during load
Error: Cannot require "screen" module before app is ready
at process.atomBinding (C:\Users\Administrator\AppData\Roaming\npm\node_modu
les\electron\dist\resources\electron.asar\common\atom-binding-setup.js:7:16)
at Object. (C:\Users\Administrator\AppData\Roaming\npm\node_modul
es\electron\dist\resources\electron.asar\browser\api\screen.js:2:34)
at Object. (C:\Users\Administrator\AppData\Roaming\npm\node_modul
es\electron\dist\resources\electron.asar\browser\api\screen.js:8:3)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)

Windows 7

Hi,

I cannot get the notification to show up on windows 7. Can someone please advise?

Thank you

Dynamic template and icon - Cleaning up each notification after it is closed is necessary

I've written some logic that allows one to dynamically change the icon and template based on params passed to electron-notify:

  let setNotificationTemplate = level => {

    let templatePath = (process.env.NODE_ENV === 'development')
      ? Path.join(__dirname, `../../../dist/notification-templates/${level}.html`)
      : Path.join(__dirname, `./notification-templates/${level}.html`)
      
    mb.window.webContents.send('debug-error', templatePath)

    eNotify.setTemplatePath(templatePath)
  }

  let setNotificationIcon = icon => {

    let appIcon = (process.env.NODE_ENV === 'development')
      ? Path.join(__dirname, `../../../dist/imgs/${icon}.png`)
      : Path.join(__dirname, `./imgs/${icon}.png`)
      
    mb.window.webContents.send('debug-error', appIcon)

    eNotify.setConfig({appIcon})
  }

This works! However, the notification needs to be cleaned up after it has shown, or it will retain the previous parameters.

Has anyone come across a way to do this without calling closeAll() before each notification?

Double click event!

Can double click event be created for the notifications on display?
We have onclickFunc function, similary can we add event listner on double click
@hankbao

Height of the notification constraints

It appears that the height of the notification must be an exact multiple of the animation steps. If it is not, then in moveNotificationAnimation() notificationWindow.setPosition will throw an exception

    at TypeError (native)
    at Timeout._repeat (C:\Users\t_kevinki\pulse-electron\app\node_modules\electron-notify\index.js:424:24)

That is because step will not be an integer if the height is not a multiple of steps. Maybe casting to int will fix it?

Notification Position

Can you add an option on the notification where you can specify the notification position to show

top-right
bottom-right

..etc.

Click on (tray) notification on linux not working properly.

I have 2 apps installed based on electron. Clicking on the notification opens both apps present. For example clicking on mailspring notification, also opens up telegram, and visa versa.

My OS is ubuntu 17.10. It seems this is linux issue.

Steps to reproduce:

  1. Install & configure mailspring
  2. Install telegram
  3. Send mail to mailbox.

Bug:

Telegrams also opens.

修复一个bug

notificationWindow.setPosition(config.firstPos.x, startY + curStep * step)
改成
notificationWindow.setPosition(config.firstPos.x, parseInt(startY + curStep * step))

onCloseFunc called on timeout after onClickFunc fired

onCloseFunc fires if the notification times out. That's great. But it also happens after onClickFunc fired which is pretty bad. Also the notification should disappear after I clicked it.

Removing the notification on click via closeAll() is erroneous, too. Throws an exception object already destroyed.

node 6.2.1, Win7/10 @32bit

Notification not show on top when win.setAlwaysOnTop is used

When I use win.setAlwaysOnTop in my BrowserWindow the notification is shown behind the BrowserWindow.
Does anyone have any ideas?

config = {
width: 380,
height: 70,
borderRadius: 5,
displayTime: 5000,
...
defaultWindow: {
alwaysOnTop: true,
skipTaskbar: true,
resizable: false,
show: false,
frame: false,
transparent: true,
...
}
};

Error: Object has been destroyed

Error & Stack Trace
Error: Object has been destroyed
at D:\ionic\demos\electron\HK-hardika\myapp-source\node_modules\electron-notify\index.js:309:23
at AnimationQueue.animate (D:\ionic\demos\electron\HK-hardika\myapp-source\node_modules\electron-notify\index.js:28:15)
at D:\ionic\demos\electron\HK-hardika\myapp-source\node_modules\electron-notify\index.js:32:20
at

Code:

function A(){
     eNotify.closeAll();
  eNotify.setConfig({
    animateInParallel: true,
    appIcon : path.join(__dirname, "./logo.ico")
  });

  eNotify.notify({ 
    title: 'Your offline data are being synced to online', 
    text: 'Please wait a while' 
  });
  setTimeout(function(){
    otherFunction();
  },3000)
}

otherFunction(){
   eNotify.closeAll();
  
  eNotify.setConfig({
    animateInParallel: true,
    appIcon : path.join(__dirname, "./logo.ico"),
    displayTime: 5000 
  });

  eNotify.notify({ 
    title: 'Your offline data are synced successfully', 
    text: 'Please wait while we redirect you'
  });
}

Is this still maintained?

Hey,

It's fascinating to see an Electron notification management package supporting both queues and duration time(honestly it'd be a go-to solution for our project). However, it seems to be out of active maintenance:

  • there were no further releases since v0.1.0
  • some of the issues are still open(e.g. #2)

Do you plan on fulfilling feature requests and fixing bugs or you're looking for contributors?

Thanks in advance.

Notification Window Not Closable from Render Process

I can't seem to figure out why I am unable to close the notification window from the render process. I have made a couple of changes from recent pull requests i've gone through. See this fork for updated code.

There is no error dumped to console it just doesn't close. It auto closes properly and fires the callback for onClose. It also fires the callback for onShow too. The onClick callback does not seem to work.

Any suggestions on how to make this dump an error or make this work?

Exception on shutdown

It appears that there is a problem that exists on the shutdown.
If Electron is shut down while notifications exist, I get this error below.

Looks like the async animation is not terminated properly on the app shutdown.

main error= Error: Object has been destroyed
at Error (native)
at Timeout._repeat (...\node_modules\electron-notify\index.js:424:24)
at Timeout.wrapper [as _onTimeout] (timers.js:425:11)
at tryOnTimeout (timers.js:232:11)
at Timer.listOnTimeout (timers.js:202:5)

Error first time call this package

When put this code and run itu . I got some error
thi what I put in my code
var eNotify = require('electron-notify'); // Send simple notification eNotify.notify({ title: 'Notification title', text: 'Some text' });

the error
notify

No notification shows in production build

Notifications how in dev environement but not in production

"electron-notify": "^0.1.0",
"electron": "^4.0.0",

config:

eNotify.setConfig({
        appIcon: path.join(__dirname, wlmIcon),
        displayTime: 10000,
        borderRadius: 0,
        defaultStyleContainer: {
          backgroundColor: Colors.primary2,
          overflow: "hidden",
          padding: 8,
          border: "none",
          fontFamily: "Courier",
          fontSize: 12,
          position: "relative",
          lineHeight: "15px",
          color: Colors.textColor2
        },
        defaultStyleClose: {
          display: "none"
        },
        defaultStyleText: {
          margin: 0,
          overflow: "hidden",
          cursor: "default",
          color: Colors.textColor2
        }
      });

top-level import throws error

Having

import notif from 'electron-notify'
// or
const whatever = require('electron-notify')

throws Error: Cannot initialize "screen" module before app is ready.

I "fixed" this by importing it on app.ready but it should be mentioned in the README.

electron-prebuilt 1.0+
Win7 /64

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.