Why isn't a notification generated javascript? - javascript

This is my code
var notification = new Notification('notify');
Do I have to invoke the notification or should this be enough? I have also tried the code on the mdn website which is.
Notification.requestPermission();
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
console.log("granted")
var notification = new Notification("Hi there!");
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== "denied") {
console.log("denied")
Notification.requestPermission().then(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification("Hi there!");
}
});
}
// At last, if the user has denied notifications, and you
// want to be respectful there is no need to bother them any more.
}
The function is called and the word "granted" is logged so it seems like we permissions but for some reason I see no notification either on chrome or safari? I am using local host. Why am I not seeing a notification?

The code sample you provided works fine on my Chrome, you can test it in an online editor if you have any doubts.
Here you can try an example, i just scraped https://js.do/code/552731 with your sample.
Does it work here ?
I'm not sure the issue is related with the code sample you provided.
EDIT: After checking, it might be related to https/http issues, you might want to look into this thread

Related

HTML5 Web Notification Permission Issue

I'm trying to implement HTML5 Notification API in my chat application. When I'm working on my localhost, everything works fine (The browser prompts me whether i need to allow notification from this site or not).
But when i try to access my application running in my local machine from some other machine which all connected in the same network. The browser is not prompting anything.
To Sum up my problem:
http://localhost:3000/home - This works!
http://10.1.0.126:3000/home - This doesn't works this way. (Even if try my from my computer or from other computer)
This is the code I'm using for notification api implementation
function createNotification(response){
if(!('Notification' in window)){
console.log("This browser does not Notification")
}else{
if(Notification.permission === 'granted'){
createNotification(response) // function to createNotification from response
}else if(Notification.permission !== 'denied'){
Notification.requestPermission((permission) => {
if(permission === 'granted'){
createNotification(response)
}
})
}
function createNotification(response){
// Construct the Notification
let title = response.sender_name
let notificationOptions = {
body: response.message,
icon: default_profile_pic
}
// Close the Notification after 3 seconds
let notification = new Notification(title, notificationOptions)
setTimeout(notification.close.bind(notification),3000)
}
P.S: I'm using ReactJS, Redux for my front-end development.
In Chrome 62 and newer you cannot request notification api at all unless the site is https:// secured. (see issue 779612) If you do have https on the site you should be able to use notifications and background push notifications.
https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API

Create notification by webworker

In article about notifications Mozzila says:
Note: This feature is available in Web Workers.
Worker can be created without any warnings
var worker = new SharedWorker('scripts/worker.js');
But when I try to do this inside shared worker:
var notification = new Notification("Hi there!");
It doesn't work. Webworker works fine, it does a XMLHttpRequest, it can read data from main thread and push messages to it but notification doesn't appear. I can't debug it because console is unavailable inside webworker. Permission was granted in main thread and the notifications are also available here.
If it is important I use Chrome 47.0.2526.111 m for developing and debugging. I noticed that Facebook invokes notifications even when FB tab is closed so I am trying to implement something similar.
You are doing something wrong. I had absolutely no problems running notifications in web workers.
This code works perfectly on jsfiddle:
Worker example
SharedWorker example
Please try following code:
main.js
var worker = new SharedWorker("worker.js");
worker.port.start();
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
worker.port.postMessage({name:"notification"});
}
});
worker.js
function workerFN() {
function onmessage(e) {
switch(e.data.name) {
case "notification" :
console.log("Notification:");
var notification = new Notification("Hi there!");
break;
default:
console.error("Unknown message:", e.data.name);
}
}
self.onconnect = function(e) {
for(var i=0,l=e.ports.length; i<l; i++) {
e.ports[i].addEventListener('message', onmessage);
e.ports[i].start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
}
}
}
Also console works quite well for me in web workers.

how to check speech recognition is supported by browser

My website has index.html and voice.html.
If someone navigates to voice.html,they should redirect to index.html if voice recognition is not supported by the browser.
if (!code to check if voice recognition is not supported by the browser)
{
redirect to index.html
}
I am using annyang.js.
If i open voice.html. From OPERA it should redirect to index.html. Because I think opera does not support voice recognition.
This piece of code should be able to handle the concerns.
if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
// speech recognition API supported
} else {
// speech recognition API not supported
//redirect to another page
location.href = "index.html";
}
What exactly you need to do for detection, depends on what exactly you mean by voice recognition. If you mean Chrome's x-webkit-speech, this should work:
if (document.createElement('input').webkitSpeech === undefined) {
location.href = "index.html";
}
It looks like you can just run a truthy check for annyang:
if (!annyang) {
location.href = 'index.html';
}

Failed to construct Notification: Illegal constructor

My site uses desktop notifications which have never worked on mobile devices but I've recently started to receive the following exception in Chrome Version 42.0.2311.108 on Android 4.4:
Failed to construct 'Notification': Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead. TypeError: Failed to construct 'Notification': Illegal constructor. Use ServiceWorkerRegistration.showNotification() instead.
My notification code is simple, after checking if the user has granted permissions I initialize a new Notification object as follows:
var notification = new Notification(messageOptions.title, { icon: messageOptions.icon });
How do I change this code to use the ServiceWorkerRegistration.showNotification, which comes up as undefined, to support notifications in the mobile version of Chrome or if that isn't possible do a feature detection and prevent the exceptions from happening if this really isn't supported [yet].
See crbug.com/481856 on the Chrome issue tracker:
new Notification() is on the path to deprecation, because it implicitly assumes that the page will outlive the notification, which is very unlikely on mobile (and far from guaranteed on desktop too).
Hence we will never implement it on Android. We might one day remove it on desktop too, after a deprecation period.
Websites should use ServiceWorkerRegistration.showNotification() (see spec) instead whenever it is available.
The best way I can think of to feature-detect new Notification() is to try it (before you have permission) and catch the error:
function isNewNotificationSupported() {
if (!window.Notification || !Notification.requestPermission)
return false;
if (Notification.permission == 'granted')
throw new Error('You must only call this *before* calling Notification.requestPermission(), otherwise this feature detect would bug the user with an actual notification!');
try {
new Notification('');
} catch (e) {
if (e.name == 'TypeError')
return false;
}
return true;
}
You could then use it like this:
if (window.Notification && Notification.permission == 'granted') {
// We would only have prompted the user for permission if new
// Notification was supported (see below), so assume it is supported.
doStuffThatUsesNewNotification();
} else if (isNewNotificationSupported()) {
// new Notification is supported, so prompt the user for permission.
showOptInUIForNotifications();
}
According to this:
Note: Trying to create a notification inside the ServiceWorkerGlobalScope using the Notification() constructor will throw an error.
If you want to send notification in a Service Worker, use self.registration.showNotification(). See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification

Chrome Rich Notifications - How to use it

For 2-3 days I'm trying to use Chrome rich notification. I've read some reviews regarding this but nobody tells how to use implement it.
I want to try it in a html test page. How can I do this? because I couldn't manage to show at least a basic notification... :(
I want to implement this in an extension that I'm building. How can I do this? There are special instructions?
I don't need this simple notification:
function notifyMe() {
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
else if (Notification.permission === "granted") {
var notification = new Notification("Message");
}
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
if(!('permission' in Notification)) {
Notification.permission = permission;
}
if (permission === "granted") {
var notification = new Notification("Message");
}
});
}
}//--Notification code--
I need rich notification because I need a bunch of options which this is offering.
Can someone help me with a tutorial or a html test page to understand how to implement it?
1) You can't use most of chrome APIs outside extensions with proper permissions. So you cannot test it in a standalone HTML file - unless it's packed in an extension, i.e. an options page.
So you can add a test.html file to an extension's folder, and open it as
chrome-extension://yourExtensionIdHere/test.html
It might be easier to test it in the background script though.
2) Well, you need to read the docs! There's also some examples in this article.
Points to remember:
You need to declare the "notifications" permission.
You can't use them in a content script.
Icon is required.
Callbacks (even doing nothing) are required (this was a bug until Chrome 42).
I highly recommend using a diagnostic callback:
function diag() {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
}
}
chrome.notifications.create(id, options, diag);
It will warn you of any errors while using the API.

Categories

Resources