Cordova PushNotification of Undefined - cordova-plugins

I have checked all the solutions for the same questions. But still can't solve the issue. I'm using visual studio and cordova application.
Added the phonegap-plugin-push and corresponding code has been added. Using the ngCordova $cordovapushV5. Getting PushNotification of undefined error, i've checked in physical device and tried android version 5.1 and 6.2.1.
Added script files in below order.
<script src="scripts/angular.js"></script>
<script src="scripts/ng-cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
app.run(function ($http, $cordovaPushV5) {
var options = {
android: {
senderID: "xxxxxx"
},
ios: {
alert: "true",
badge: "true",
sound: "true"
},
windows: {}
};
// initialize
$cordovaPushV5.initialize(options).then(function () {
// start listening for new notifications
$cordovaPushV5.onNotification();
// start listening for errors
$cordovaPushV5.onError();
// register to get registrationId
$cordovaPushV5.register().then(function (registrationId) {
// save `registrationId` somewhere;
})
});
// triggered every time notification received
$rootScope.$on('$cordovaPushV5:notificationReceived', function (event, data) {
// data.message,
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData
alert(data.message);
});
// triggered every time error occurs
$rootScope.$on('$cordovaPushV5:errorOcurred', function (event, e) {
// e.message
alert(e.message)
});
});

Related

How do I display console log in electron app

I'm currently creating a JS Desktop App using Electron. I'm able to get everything functional how I want it, but I want to be able to update the users on certain tasks and also display errors in the app itself.
Is there any way to add a section (terminal if you will) or something similar inside the UI, so I can log things out to the user?
Providing application feedback to your user is as simple as having a statusUpdate function in your main process send
a message (via your preload.js script) to your render process. Within your render process, listen for a message on the
assigned channel and once received, update the content of your DOM element.
main.js (main process)
// Import required electron modules
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;
// Import required Node modules
const nodePath = require('path');
// Prevent garbage collection
let window;
function createWindow() {
const window = new electronBrowserWindow({
x: 0,
y: 0,
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: nodePath.join(__dirname, 'preload.js')
}
});
window.loadFile('index.html')
.then(() => { window.show(); });
return window;
}
electronApp.on('ready', () => {
window = createWindow();
statusTest();
});
electronApp.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
electronApp.quit();
}
});
electronApp.on('activate', () => {
if (electronBrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// ---
function statusTest() {
let counter = 1;
let message;
setInterval(() => {
statusUpdate(`Status message ${counter} from main process.`);
counter++;
}, 1000);
}
function statusUpdate(message) {
window.webContents.send('statusMessage', message);
}
preload.js (main process)
// Import the necessary Electron modules
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;
// Exposed protected methods in the render process
contextBridge.exposeInMainWorld(
// Allowed 'ipcRenderer' methods
'ipcRenderer', {
// From main to render
statusMessage: (message) => {
ipcRenderer.on('statusMessage', message);
}
}
);
index.html (render process)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Electron Test</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';"/>
</head>
<body>
<label for="status">Status: </label>
<textarea id="status" cols="40" rows="10" disabled></textarea>
</body>
<script>
let status = document.getElementById('status');
window.ipcRenderer.statusMessage((event, message) => {
status.value += message + '\n'; // Append message
status.scrollTop = status.scrollHeight; // Show last entry
});
</script>
</html>

sending value url from ipcRender to ipcMain

Hey i am making a project where i want to send data to ipc main
my index.js
const {app, BrowserWindow , ipcMain} = require('electron')
const ejse = require('ejs-electron')
app.on('ready', () => {
ipcMain.on("getUrl",(event,url)=>{
console.log(url);
})
mainWindow = new BrowserWindow({
autoHideMenuBar: true,
icon: __dirname + '/logo.ico',
webPreferences: {
devTools: false,
nodeIntegration:true,
webviewTag:true
}
})
mainWindow.loadURL('file://' + __dirname + '/files/index.ejs');
})
index.ejs contains a anchor tag with value as link
<button id="dw" style="display: none;"><a class="button" id="dwl" onclick="heal()" value="#">Download</a></button>
<script src=download.js></script>
download.js i am able to alert the link but ipcRender not working
const { ipcRenderer } = require("electron");
function heal(){
var url = document.getElementById("dwl").value;
alert(url);
ipcRenderer.send("getUrl",url);
}
i am not able to send url from ejs file to main index.js file alert is working in download.js but some error in sending data to main file console.log is not working
The use of contextBridge within your preload.js script safely exposes API's you approve for use in your render
scripts.
Whist understanding how all this works can be challenging at first, becoming familiar with the below content and the
following code should put you in good stead for a solid understanding of how you can wire up your application.
Context Isolation
contextBridge
Enabling Content Isolation for remote content
Inter-Process Communication
ipcMain
ipcRenderer
webContents - contents.send(channel, ...args)
Some people like to implement concrete functions within their preload.js script(s). In this example,
the preload.js script is only used to configure whitelisted channel names for use between the main process and render
process(es). This keeps your code seperated. IE: Separation of concerns.
Let's set the channel name getUrl within the ipc.render.send array.
preload.js (main process)
// Import the necessary Electron components.
const contextBridge = require('electron').contextBridge;
const ipcRenderer = require('electron').ipcRenderer;
// White-listed channels.
const ipc = {
'render': {
// From render to main.
'send': [
'getUrl' // Channel name
],
// From main to render.
'receive': [],
// From render to main and back again.
'sendReceive': []
}
};
// Exposed protected methods in the render process.
contextBridge.exposeInMainWorld(
// Allowed 'ipcRenderer' methods.
'ipcRender', {
// From render to main.
send: (channel, args) => {
let validChannels = ipc.render.send;
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, args);
}
},
// From main to render.
receive: (channel, listener) => {
let validChannels = ipc.render.receive;
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`.
ipcRenderer.on(channel, (event, ...args) => listener(...args));
}
},
// From render to main and back again.
invoke: (channel, args) => {
let validChannels = ipc.render.sendReceive;
if (validChannels.includes(channel)) {
return ipcRenderer.invoke(channel, args);
}
}
}
);
Let's set the webPreferences.contextIsolation value to true and specify the webPreferences.preload path.
webPreferences.nodeIntegration can be set to false, but in doing so webPreferences.contextIsolation should be
set to true to "truly enforce strong isolation and prevent the use of Node primitives".
Lastly, let's listen for a message from the render process on the getUrl channel.
main.js (main process)
const electronApp = require('electron').app;
const electronBrowserWindow = require('electron').BrowserWindow;
const electronIpcMain = require('electron').ipcMain;
const nodePath = require("path");
// Prevent garbage collection
let window;
function createWindow() {
const window = new electronBrowserWindow({
x: 0,
y: 0,
width: 800,
height: 600,
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: true,
preload: nodePath.join(__dirname, 'preload.js')
}
});
window.loadFile('index.html')
.then(() => { window.show(); });
return window;
}
electronApp.on('ready', () => {
window = createWindow();
});
electronApp.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
electronApp.quit();
}
});
electronApp.on('activate', () => {
if (electronBrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
// Listen for a message on the 'getUrl' channel
electronIpcMain.on('getUrl', (event, url) => {
console.log(url);
})
This file is fairly standard and easy to understand. Just adapt code for use with .ejs
Added Javascript code in between <script> tags for sake of brevity.
index.html (render process)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Electron Test</title>
</head>
<body>
<input type="button" id="dwl" value="#">
</body>
<script>
let button = document.getElementById('dwl');
button.addEventListener('click', () => {
// Send URL on the 'getUrl' channel
window.ipcRender.send('getUrl', button.value);
});
</script>
</html>

Simple Service worker notification click not working

I'm trying to get notification click events from notifications in Chrome (Windows 10). When the service activates, it will automatically show a notification message with two buttons on it. Clicking either button should cause the notification click handler to fire, but it doesn't.
Here's a simple example.
CLIENT.JS:
self.addEventListener('install', function (event) {
console.log(">>> installing client service worker");
self.skipWaiting();
});
self.addEventListener('activate', function (event) {
console.log('>>> client service activated');
showNotificationMessage("xxx", "yyy", "123");
});
self.addEventListener('notificationclick', function (event) {
console.log('>>> On notification click: ', event.notification.tag);
});
function showNotificationMessage(messageTitle, bodyMessage, data) {
registration.showNotification(messageTitle, {
actions: [{ action: "a", title: "action a" }, { action: "b", title: "action b", }],
body: bodyMessage,
requireInteraction: true,
renotify: true,
tag: 'test',
data: data
}).then(console.log('>>> notification was successful')).catch(function (error) {
console.log(">>> showNotification error: " + error);
});
}
CLIENT.HTML
<!DOCTYPE html>
<html>
<head>
<script>
if ('serviceWorker' in navigator) {
// Register service worker
navigator.serviceWorker.register('Client.js').then(function (reg) {
console.log("SW registration succeeded. Scope is " + reg.scope);
}).catch(function (err) {
console.error("SW registration failed with error " + err);
});
}
</script>
</head>
<body>
When this page loads, a notification should be displayed from the service worker. Clicking the action buttons should cause a notification click event in the service worker, but it doesn't.
</body>
</html>

React component intermitently working in chrome, debug for stability

This code has been working fine, but now it's working intermittently in chrome. Does anyone know what might be causing this. If so what can I do to increase stability in chrome
This function opens a pop up modal with the project form react component.
editProject: function(i) {
$('#agency_projects').trigger(
"projects:open",
[this.state.projects[i].showUrl, true]
);
},
getInitialState: function() {
return {
...
/* TODO Refactor to prevent props in initialState */
projectId: this.props.projectId,
projectUrl: this.props.projectUrl,
}
},
The initial state has the project id, and url stored which is used to submit an ajax request to pull in the project.
componentDidMount: function() {
if(this.props.projectUrl) {
$.getJSON(this.state.projectUrl)
.done(function(data) {
if(!this.isMounted()) {
return;
}
this.setState({
title: data.title,
externalUrl: data.externalUrl,
client: data.client,
description: data.description,
content: data.content,
});
}.bind(this))
.fail(function(jqXHR, status, err) {
console.error(jqXHR, status, err);
});
}
},
The form renders as suspected, but the data is only pulled every now and again.

Cordova device plugin not working, deviceready returns other object than the expected device

I'm using cordova device plugin, and I have this in my main js:
$(document).ready(function(){
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady(device) {
console.log(device);
}
}
For some reason, the result of the device object is:
{
bubbles: false,
cancelBubble: false,
cancelable: false,
clipboardData: undefined,
currentTarget: null,
defaultPrevented: false,
eventPhase: 0,
returnValue: true
//...
}
I just tried with an iPhone (I don't have an Android here) and have installed cordova plugin add cordova-plugin-device already, of course I have <script type="text/javascript" charset="utf-8" src="cordova.js"></script> in my html and even it has worked in the past.
Any suggestion of what can be happening?
Ok, I answer myself, I was stupid, just had to remove 'device' from the params so instead of
function onDeviceReady(device) {
console.log(device);
}
it is
function onDeviceReady() {
console.log(device);
}

Resources