ionic 3 in-app-browser get click event in app - ionic-framework

ionic 3 in-app-browser get click event in ionic app
Hear is my code
let target = "_blank";
const browser = this.iab.create(url,target,this.options);
browser.on('loadstop').subscribe(event => {
browser.executeScript({code: `$("[data-menu=logout]").attr('data-menu','logout_custom');
$("[data-menu=logout_custom]").attr('href',url);
$("[data-menu=logout_custom]").on('click',function(){
webkit.messageHandlers.cordova_iab.postMessage('REACT_EXIT');
this.backendMessage('REACT_EXIT')
})
`});
});
this.backendMessage('REACT_EXIT') this function is in my ionic app
I need to call this function on click of logout_custom

Try this
let target = "_blank";
const browser = this.iab.create(url,target,this.options);
browser.on('loadstop').subscribe(event => {
console.log(event,"loadstop");
browser.executeScript({code: $("[data-menu=logout]").attr('data-menu','logout_custom');
$("[data-menu=logout_custom]").click(function(){
var message = 'REACT_EXIT';
var messageObj = {my_message: message};
var stringifiedMessageObj = JSON.stringify(messageObj);
window.webkit.messageHandlers.cordova_iab.postMessage(stringifiedMessageObj);
});}).then((cookie) =>{
console.log(cookie,"cookie");
}).catch((error)=>{
console.log(error,"error");
});
});
browser.on('message').subscribe((event) => {
console.log('postmessage received',event);
const postObject:any = event
if(postObject.data.my_message == 'REACT_EXIT'){
console.log(postObject.data.my_message);
}
console.log('other message');
})

Related

When i click a button, it displays many alerts, stacks and overlaps

i want to sync the task, which when i click sync on the side menu, it will call the function in data.service.ts and it will display alert.
private async presentAlert(message) {
const alert = await this.alertCtrl.create({
message: message,
buttons: ['OK']
});
await alert.present();
}
this is the code, where i want to sync the task on data.service.ts
sync_task()
{
let body = new FormData();
body.append('access_token', localStorage.getItem('access_token'));
this.apiService.syncDataFromForm('/tasks', body)
.then((result: any) => {
if(result.data)
{
let form_data = result.data;
console.log("task synced");
console.log(form_data);
this.deleteTask();
this.deleteTaskList();
this.deleteBuildingDetails();
console.log(form_data);
for(let data of result.data) {
var submission_id = data.submission_id;
var project_name = data.project_name;
var status = '0';
var building_submission_id = data.building.submission_id;
var building_data = JSON.stringify(data.building.data);
console.log("building_data");
console.log(building_data);
this.insertTask(submission_id, project_name, status);
for(let formData of data.data)
{
console.log("all form data");
console.log(formData);
var form_id = formData.form_id;
var data_id = formData.id;
var form_name = formData.form_name;
var submission_group = formData.submission_group;
console.log("form_id");
console.log(formData.form_id);
this.insertTaskList(submission_id, data_id, form_id, form_name,submission_group);
}
this.insertBuildingDetails(submission_id, building_submission_id, building_data);
}
this.authState.next(false);
this.presentAlert('Successfully synced!');
this.menuCtrl.close();
this.router.navigateByUrl('home');
} else {
this.presentAlert('Uh oh!, sync failed! ');
}
});
}
this code in side menu
sync_task()
{
this.data.sync_task();
}
i don't know why the alert display too many times. the alert stacking up until the background turns dark. and i need to click ok too many times to clear that.

Use cordova plugin on ionic 3 app (cordova-androidwear)

I have an ionic 3 app who shown markers on a map. But now I have a new request for the app to port it to wereable devices (Android wear and Apple watch). Show the markers in a map on the watch and some info...
After a lot of search and any questions on forums, I get a android wear plugin https://github.com/tgardner/cordova-androidwear but it is a cordova plugin.
The code in cordova is:
function watch(handle) {
var self = this;
AndroidWear.onDataReceived(handle, function(e) {
self.dataReceived(e.data);
});
self.handle = handle;
}
watch.prototype = {
dataReceived: function(data) {
app.logEvent("AndroidWear message received: " + data);
},
sendMessage: function(message) {
AndroidWear.sendData(this.handle, message);
app.logEvent("AndroidWear message sent!");
}
};
var app = {
watch: null,
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
var self = this;
document.addEventListener('deviceready', function() {
self.onDeviceReady();
}, false);
},
onDeviceReady: function() {
var self = this;
self.receivedEvent('deviceready');
if(AndroidWear) {
AndroidWear.onConnect(function(e) {
self.logEvent("AndroidWear connection established");
self.watch = new watch(e.handle);
});
}
var sendButton = document.getElementById("sendMessage");
sendButton.addEventListener("click", function() {
if(self.watch) {
self.watch.sendMessage("Mensaje");
}
});
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
this.logEvent('Received Event: ' + id);
},
logEvent: function(message) {
var events = document.getElementById("events");
var el = document.createElement("li");
el.innerHTML = message;
events.appendChild(el);
}
};
But I need to translate the cordova code to ionic code.
I try that:
(<any>window).AndroidWear.onConnect(() =>{
console.log("Androidwear : CONECTADO " );
})
(<any>window).AndroidWear.onDataReceived((data) =>{
console.log("Plugin: " + data);
})
But I received an execution error like this
[INFO:CONSOLE(13355)] "Didn't set nav root: TypeError: window.AndroidWear.onConnect(...) is not a function", source: file:///android_asset/www/build/main.js (13355)
I never translate the Cordova code into ionic 3, so maybe I've had stupid mistakes.
How can I translate that code to use the android-wear plugin on ionic 3 app?
Thanks you.

Ionic - Facebook Native Ads Error 1001 (No fill)

My facebook native ads integration code is like below.
var that = this;
this.platform.ready().then(() => {
if(FacebookAds)
{
//FacebookAds.setOptions({
//isTesting: true,
//deviceHash: 'fe645f07-9801-41fe-a430-xxxxxxxxxxx'
//},(s)=>(console.log("settings are OK.")),(e)=>(console.log("Settings are not loaded...")));
FacebookAds.createNativeAd('xxxxxxxxx',
(eee) => {
document.addEventListener("onAdLoaded", (data) =>{
console.log(data);
let temp: any = data;
if(temp.adType == "native")
{
this.startFB = 1;
document.getElementById('adIcon').setAttribute("src", decodeURIComponent(temp.adRes.icon.url));
document.getElementById('adCover').setAttribute("src", decodeURIComponent(temp.adRes.coverImage.url));
document.getElementById('adTitle').innerHTML = temp.adRes.title;
document.getElementById('adBody').innerHTML = temp.adRes.body;
document.getElementById('adSocialContext').innerHTML = temp.adRes.socialContext;
document.getElementById('adBtn').innerHTML = temp.adRes.buttonText;
that.updateXY(0, 0);
}
});
document.addEventListener('onAdFailLoad', (data) => {
console.log(data);
//alert('error: ' + data);
});
},
(err) => console.log(err)
);
}
});
When I run this code without test mode, I get 1001 error code.
When I run this code with test mode, No error but load data comes empty.
Not: I test code in real device and I login as test user to Facebook app in this device.
Do you have any advice?

ionic push notification when app is in foreground

I am making a ionic 3 app. I want notifications to appear even when app is in foreground. I have tried using FCM Plugin I'm getting notifications only when app is in background.
Home.ts
import { AngularFireDatabase } from 'angularfire2/database';
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import firebase from 'firebase';
declare var FCMPlugin;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
firestore = firebase.database().ref('/pushtokens');
firemsg = firebase.database().ref('/messages');
constructor(public navCtrl: NavController,public afd:AngularFireDatabase) {
this.tokensetup().then((token)=>{
this.storeToken(token);
})
}
ionViewDidLoad() {
FCMPlugin.onNotification(function (data) {
if (data.wasTapped) {
//Notification was received on device tray and tapped by the user.
alert(JSON.stringify(data));
} else {
//Notification was received in foreground. Maybe the user needs to be notified.
alert(JSON.stringify(data));
}
});
FCMPlugin.onTokenRefresh(function (token) {
alert(token);
});
}
tokensetup(){
var promise = new Promise((resolve,reject)=>{
FCMPlugin.getToken(function(token){
resolve(token);
},(err)=>{
reject(err);
});
})
return promise;
}
storeToken(token){
this.afd.list(this.firestore).push({
uid: firebase.auth().currentUser.uid,
devtoken: token
}).then(()=>{
alert('Token stored')
}).catch(()=>{
alert('Token not stored');
})
// this.afd.list(this.firemsg).push({
// sendername:'adirzoari',
// message: 'hello for checking'
// }).then(()=>{
// alert('Message stored');
// }).catch(()=>{
// alert('message not stored');
// })
}
}
the function cloud for notifications
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var wrotedata;
exports.Pushtrigger = functions.database.ref('/messages/{messageId}').onWrite((event) => {
wrotedata = event.data.val();
admin.database().ref('/pushtokens').orderByChild('uid').once('value').then((alltokens) => {
var rawtokens = alltokens.val();
var tokens = [];
processtokens(rawtokens).then((processedtokens) => {
for (var token of processedtokens) {
tokens.push(token.devtoken);
}
var payload = {
"notification":{
"title":"From" + wrotedata.sendername,
"body":"Msg" + wrotedata.message,
"sound":"default",
},
"data":{
"sendername":wrotedata.sendername,
"message":wrotedata.message
}
}
return admin.messaging().sendToDevice(tokens, payload).then((response) => {
console.log('Pushed notifications');
}).catch((err) => {
console.log(err);
})
})
})
})
function processtokens(rawtokens) {
var promise = new Promise((resolve, reject) => {
var processedtokens = []
for (var token in rawtokens) {
processedtokens.push(rawtokens[token]);
}
resolve(processedtokens);
})
return promise;
}
it works only when the app in the background. but when i exit from the app and it's not in the background I don't get any notification.
You need to edit the FCM Plugin files. I found the solution only for android now.
I use https://github.com/fechanique/cordova-plugin-fcm this FCM plugin for android and ios in cordova.
You need to edit file MyFirebaseMessagingService.java line 53(line no be may be differ).
In this file there is a method onMessageReceived at the end of the method there is a line which is commented, this line calling an another method i.e. sendNotification(....).
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), data);
You have to uncomment this line and change last parameter from remoteMessage.getData() to data (data variable is already there in the code).
And comment this line FCMPlugin.sendPushPayload( data );
Now you are good to go. Now you are able to receive notification even when app is opened (foreground), you will receive the banner (floating) notifications.
If you found anything for IOS please let me know!!!
I am using firebase plugin for ionic 3.
There is a check if notification data contain "notification_foreground" or not and save it in variable foregroundNotification.
if(data.containsKey("notification_foreground")){
foregroundNotification = true;
}
then it create showNotification variable which decide if we need to show notification or not and pass this to the sendMessage (show notification function).
if (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title) || (data != null && !data.isEmpty())) {
boolean showNotification = (FirebasePlugin.inBackground() || !FirebasePlugin.hasNotificationsCallback() || foregroundNotification) && (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title));
sendMessage(data, messageType, id, title, body, showNotification, sound, vibrate, light, color, icon, channelId, priority, visibility);
}
your payload should contain notification_foreground, notification_title and notification_body.

File Transfer , onProgress not working on iOS ( IONIC3 )

I been working with fileTransfer from Ionic native, it working fine on Android, but on iOS not not do anything at all
Here is my code:
getFile(fileName,url){
let fileTransfer: FileTransferObject = this.transfer.create();
fileTransfer.download(url, this.file.dataDirectory + fileName).then((entry) => {
console.log('entry:',entry)
}, (error) => { console.log(error); });
console.log('file transfer',fileTransfer.onProgress)
var a = fileTransfer.onProgress((progressEvent: ProgressEvent) => {
this.ngzone.run(() => {
console.log(progressEvent.loaded)
});
});
}
it depends on how to derive this.file.dataDirectory.
In my case it always works like this ..
declare var cordova:any; //on top of file
if (this.platform.is('android')) {
this.fsurl = cordova.file.dataDirectory;
}else{
this.fsurl = cordova.file.documentsDirectory;
}