How to add a push notification to a website? - javascript

I am trying to add a push notification to my website. When the user logs in they will be presented with a notification reminding them to add their results. I found code off chrome pop ups but it dosen't seem to be working.
<script>
Notification.requestPermission(function(status) {
console.log('Notification permission status:', status);
});
function displayNotification() {
if(Notification.permission=="granted"){
jQuery('#notification-head').hide();
notify=new Notification("New Blog Available",{
body:"Demo paragraph",
icon:'bg-Img.png',
tag:'12222'
});
notify.onclick=function(){
notify.close();
}
}
</script>

You need to add a curly brace at the end of your function. You can look at this example. Also, you are never calling the displayNotification, you need to use this:
Notification.requestPermission(function(status) {
console.log('Notification permission status:', status);
displayNotification();
});
function displayNotification() {
if(Notification.permission == "granted"){
$('#notification-head').hide();
let notify = new Notification("New Blog Available", {
body:"Demo paragraph",
icon:'bg-Img.png',
tag:'12222'
});
notify.onclick = function(){
notify.close();
}
}
}

Related

How to show custom page loading error when "No Internet Available"?

I want to generate a custom error page when there's No internet available in a website just like https://m.apkpure.com and page will load again on refresh when internet is available. I know we can use the following code to check "ONLINE" or "OFFLINE"
window.addEventListener("online", function() {
alert("You're ONLINE!");
});
window.addEventListener("offline", function() {
alert("You're OFFLINE!");
});
// OR
if (navigator.onLine) {
console.log("You are online");
} else {
console.log("You are offline");
}
But I dont think that the https://m.apkpure.com use the above kind of code to detect ONLINE or OFFLINE. If there's any other way to do so please let me know.
After a little digging through the source code...
In sw.js on the website you were talking about(https://m.apkpure.com):
self.addEventListener('fetch', (event) => {
if (!self.navigator.onLine) {
event.respondWith(
caches.match(event.request).then((response) => {
return caches.match('/offline.html')
})
)
}
})
So yeah, they do use navigator.onLine.

Problems with ionic back button

I have a problem with the back button of my application.
Initially I thought that the problem was in Cordova, but I have identified that the problem is actually in Ionic.
I found this code while researching for a solution:
// Disable BACK button on home
$ionicPlatform.registerBackButtonAction(function (event) {
if($state.current.name=="app.home"){
navigator.app.exitApp();
}
else {
navigator.app.backHistory();
}
}, 100);
However, it is giving the following error:
Uncaught ReferenceError: $ionicPlatform is not defined
I am putting that code within a new document called functionAngular.js and I add it at the end of the body tag. As I must inform this function ?
My problem is that:
I want my back button to send the user further back in the navigation stack instead of closing the application instantly.
I am grateful for this help.
I recommend you first add $ionicPlatform in controller, and in the first controller loaded, test every state (see below) that the back button should have different actions.
$ionicPlatform.registerBackButtonAction(function () {
if ($state.current.name == " login (example) ") {
ionic.Platform.exitApp();
}
if ($state.current.name == " main menu buttons (example) ") {
// Sample message "want to exit the application?" (YES/NO)
if (YES) {
$ionicViewSwitcher.nextDirection('back');
$state.go(' ????');
};
};
if ($state.current.name == " order (example) ") {
// Sample message "want to exit the order?" (YES/NO)
if (YES) {
$ionicViewSwitcher.nextDirection('back');
$state.go(' ????');
};
};
}, 100);
angular.module('EGLISE')
.run(function($ionicPlatform,$state,$ionicHistory){
$ionicPlatform.registerBackButtonAction(function (event) {
if($state.current.name=="app.home"){
navigator.app.exitApp();
}
else {
$ionicHistory.backHistory();
}
}, 100);
});
Please modify your functionAngular.js to the above code.

FB SDK Version 2.4 not returning value for /me/groups

I am trying to get the User's groups list with the following code:
$(document).ready(function() {
$("#fetchButton").click(function() {
console.log('fetch button');
FB.getLoginStatus(function(res){
if( res.status == "connected" ){ // check if logged in
// get user data first, which will be handled by an anonymours fucntion passed inline
FB.api('/me', function(meResponse) {
//console.log(meResponse);
UID = meResponse.id;
getGroups();
console.log(meResponse);
});
} else { // if not logged in, call login procedure
FB.login(function(){
$("#fetchButton").click();
}, {scope: 'publish_actions, publish_actions, read_stream, user_groups'});
}
});
});
});
function getGroups() {
FB.api('/me/groups', function(groupResponse) {
console.log(groupResponse);
});
}
This code used to work with some old version of FB SDK. But not now.
Any help!
read_stream and user_groups are deprecated and you are using publish_actions two times. In order to get a list of all the groups you manage, you need to use user_managed_groups now.
More information: https://developers.facebook.com/docs/apps/changelog#v2_4

Run JavaScript on every click within AJAX success function

I make three links on AJAX success function. I want a JavaScript function to run every time any of those links are clicked while user is on that page. I understand it is easy but I am unable to get the script run on every click. It just runs on clicking of first link and does nothing on clicking of other links. Here is the code:
request.success(function(data) {
//Put the heading on the div
//http://stackoverflow.com/questions/12898475/using-jquery-to-replace-text-inside-h3-header
var dataReceived = null;
$("#bookList h3 #spanId").text("A list appears");
for(var i=0;i<data.length;i++){
dataReceived =data[i].name;
$("#bookList").append("<a href id=bookLink>"+dataReceived+"</a>" +"<br>");
}
$("#bookLink").click(function(event){
$.getScript("information.js",function(){
dealWithData();
});
});
});
request.fail(function(jqXHR, status, errorMessage) {
if((errorMessage = $.trim(errorMessage)) === "") {
alert("An unspecified error occurred. Check the server error log for details.");
}
else {
alert("An error occurred: " + errorMessage);
}
});
dealWithData for now just has an alert:
function dealWithData(){
alert("Reached here");
}
Any help is appreciated. Thanks.
I don't like using .click() any more since it has been deprecated. You should also change it to use:
.on("click", function(event) {

Can’t get push notifications in Android to work using ngCordova

I'm having a tough time getting push notifications (using the ngCordova plugin) to work. I have followed their sample code exactly as is documented on the site: http://ngcordova.com/docs/plugins/pushNotifications/
(the only difference is that I don't have a deviceready listener, instead, my code is inside the ionicPlatform.ready listener.)
Here is my code:
angular.module('myApp', ['ionic', 'ngCordova'])
.run(function($ionicPlatform, $rootScope, $state, $cordovaPush) {
$ionicPlatform.ready(function() {
var config = {
"senderID": "myID100001000"
};
$cordovaPush.register(config).then(function(result) {
alert(result);
}, function(err) {
alert(err);
})
});
$rootScope.$on('$cordovaPush:notificationReceived', function(event, notification) {
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
alert('registration ID = ' + notification.regid);
}
break;
default:
alert('An unknown GCM event has occurred');
break;
}
});
})
When my app starts I do get the "OK" alert, so I know it successfully goes through the $cordovaPush.register call. However, I was expecting to get a "registered" notification event, right after, but I never get notified.
Any help would be appreciated.
The solution is in the comments but this needs a proper answer.
First of all, the register callback always returns OK as long as you pass a senderID, but if the $cordovaPush:notificationReceived event is never called (it may take a few seconds), this ID is probably wrong.
You must use the Project Number, not the Project ID.
To get the number, go to the API Console, select the project and you'll be on the Overview page. On top of this page, you'll see something like this:
Project ID: your-project-id Project Number: 0123456789
Just copy and use the project number and everything should work.
I have suffered with this a lot and I have found out, that there are in fact two versions of the cordova push plugin currently:
https://github.com/phonegap-build/PushPlugin (deprecated)
https://github.com/phonegap/phonegap-plugin-push (new one)
Both are supported by ngCordova, but only the deprecated version is documented.
The deprecated version is $cordovaPush
and the newer one is $cordovaPushV5, and they have completely different methods.
For me the problem was that I downloaded the cordova-plugin-push and tried to implement it with the old documentation on ngCordova site.
The code is:
/*
* Non deprecated version of Push notification events
*/
function registerV5() {
$ionicLoading.show({
template: '<ion-spinner></ion-spinner>'
});
if (ionic.Platform.is('browser')) {
alert("You are running on broswer, please switch to your device. Otherwise you won't get notifications");
$ionicLoading.hide();
return;
}
/**
* Configuration doc:
* https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/API.md#pushnotificationinitoptions
*/
var GCM_PROJECT_ID = 'xxxxxx';
$cordovaPushV5.initialize({
"android": {
"clearNotifications": false,
"senderID" : GCM_PROJECT_ID
}
});
$cordovaPushV5.register().then(function (deviceToken) {
console.log("Successfully registered", deviceToken);
$scope.data.deviceToken = deviceToken;
// Below code required to configure $cordovaPushV5 notifications emitter.
// Don't pass function it's not handler.
$cordovaPushV5.onNotification();
$cordovaPushV5.onError();
$ionicLoading.hide();
}, function (error) {
console.log("Failed to registered");
console.log("error object : ", error);
$ionicLoading.hide();
});
}
$rootScope.$on('$cordovaPushV5:notificationReceived', function(event, data) {
console.log("notification received");
console.log("data object: ", data);
var foreground = data.additionalData.foreground || false;
var threadID = data.additionalData.payload.threadID || '';
var group = data.additionalData.payload.group || false;
if (foreground) {
// Do something if the app is in foreground while receiving to push - handle in app push handling
console.log('Receive notification in foreground');
} else {
// Handle push messages while app is in background or not started
console.log('Receive notification in background');
// Open FB messanger app when user clicks notification UI when app is in background.
if (typeof data.additionalData.coldstart != "undefined" && data.additionalData.coldstart == false)
if (!group)
// Open FB Messenger of specific user chat window
window.open('fb-messenger://user/' + threadID, '_system', 'location=no');
else
// Open FB Messenger of specific group chat window
window.open('fb-messenger://groupthreadfbid/' + threadID, '_system', 'location=no');
}
});
$rootScope.$on('$cordovaPushV5:errorOccurred', function(event, error) {
console.log("notification error occured");
console.log("event object: ", event);
console.log("error object: ", error);
});
More on this github article: https://github.com/driftyco/ng-cordova/issues/1125 (code from here) and in this article: https://github.com/yafraorg/yafra/wiki/Blog-Ionic-PushV5

Categories