Ionic 3 InAppBrowser not firing event - ionic-framework

I am making an ionic app where I need to call to a website(not exist). I am just trying to catch that into the error. But the "exit" event does not get fired.
Code
this.browser = this.iab.create("http://www.randomwebsite.com/", "_blank", this.options);
this.browser.on('exit').subscribe(event => {
console.log("exit -->", event);
}, err => {
console.log("InAppBrowser exit Event Error: " + err);
});
It opens the browser in the app but only shows the 404 page, but dont go further in the error code, so that I can handle it.

Declare cordova in your component
declare var cordova;
Then for the error check you can use the following function
const browser = cordova.InAppBrowser.open('http://randomwebsite.org', '_blank', this.options);
browser.addEventListener('loadstart', function(e) {
// event fires when the InAppBrowser starts to load a URL.
console.log(e);
});
browser.addEventListener('loaderror', function(e) {
// event fires when the InAppBrowser encounters an error when loading a URL.
console.log(e);
browser.close();
});
You can checkout the documentation here.

If I understand the question correctly then the main problem is to catch the error
this.browser = this.iab.create("http://www.randomwebsite.com/", "_blank", this.options);
this.browser.on('loadstop').subscribe(event => {
console.log("exit -->", event);
}, err => {
//once the page loading stops and there is an error it comes here and displays you log.
console.log("InAppBrowser exit Event Error: " + err);
});
exit event is fired when we exit the inAppBrowser

Related

Service workers "sync" operation is working while its offline?

I have a PWA project where I send the data to server. During this process, if the user is offline then the data is stored in indexedDb and a sync tag is registered. So, then when the user comes online that data can sent to the server.
But In my case the sync event gets executed immediately when the we register a sync event tag, which means the data is tried to be sent to server while its offline, which is not going to work.
I think the sync event supposed to fire while its online only, what could be issue here ?
The service worker's sync event works accordingly when I tried to enable and disable the offline option of chrome devtools, and also works correctly in my android phone.
This is how I register my sync tag
function onFailure() {
var form = document.querySelector("form");
//Register the sync on post form error
if ('serviceWorker' in navigator && 'SyncManager' in window) {
navigator.serviceWorker.ready
.then(function (sw) {
var post = {
datetime1: form.datetime1.value,
datetime: form.datetime.value,
name: form.name.value,
image: form.url.value,
message: form.comment.value
};
writeData('sync-comments', post)
.then(function () {
return sw.sync.register('sync-new-comment');
})
.then(function () {
console.log("[Sync tag registered]");
})
.catch(function (err) {
console.log(err);
});
});
}
}
And this is how the sync event is called
self.addEventListener('sync', function (event) {
console.log("[Service worker] Sync new comment", event);
if (event.tag === 'sync-new-comment') {
event.waitUntil(
readAllData('sync-comments')
.then(function (data) {
setTimeout(() => {
data.forEach(async (dt) => {
const url = "/api/post_data/post_new_comment";
const parameters = {
method: 'POST',
headers: {
'Content-Type': "application/json",
'Accept': 'application/json'
},
body: JSON.stringify({
datetime: dt.datetime,
name: dt.name,
url: dt.image,
comment: dt.message,
datetime1: dt.datetime1,
})
};
fetch(url, parameters)
.then((res) => {
return res.json();
})
.then(response => {
if (response && response.datetimeid) deleteItemFromData('sync-comments', response.datetimeid);
}).catch((error) => {
console.log('[error post message]', error.message);
})
})
}, 5000);
})
);
}
});
you mention
The service worker's sync event works accordingly when I tried to enable and disable the offline option of chrome devtools, and also works correctly in my android phone.
So I'm not sure which case is the one failing.
You are right that the sync will be triggered when the browser thinks the user is online, if the browser detects that the user is online at the time of the sync registration it will trigger the sync:
In true extensible web style, this is a low level feature that gives you the freedom to do what you need. You ask for an event to be fired when the user has connectivity, which is immediate if the user already has connectivity. Then, you listen for that event and do whatever you need to do.
Also, from the workbox documentation
Browsers that support the BackgroundSync API will automatically replay failed requests on your behalf at an interval managed by the browser, likely using exponential backoff between replay attempts.

Service Worker Fails on caches.open()

I'm trying to get a basic service worker up and running.
The problem I have is that when I run "caches.open()", the browser throws a
sw.js:1 Uncaught (in promise) DOMException: Unexpected internal error
Commenting out the caches.open removes the exception.
How can I get more information from the browser to tell me what's wrong?
Here's the service worker and registration code.
var CACHE_NAME = 'pwacache-v1';
var urlsToCache = [
'/',
'main.css'
];
self.addEventListener('install', function (event) {
// Perform install steps
console.log('install');
try {
event.waitUntil(getFiles());
} catch (ex) {
console.log(ex);
}
});
function getFiles() {
console.log('opening: ' + CACHE_NAME );
/*
triggers Uncaught (in promise) DOMException: Unexpected internal error
*/
caches.open(CACHE_NAME).then(function (cache) {
return Promise.all(
urlsToCache.map(function (url) {
console.log(url);
return cache.add(url).catch(function (reason) {
console.log([url + "failed: " + String(reason)]);
});
}) // end of map
);
});
console.log('waiting 3...')
}
And the registration code
// https://developers.google.com/web/fundamentals/primers/service-workers/registration
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('sw.js');
});
}
I do see the sw.js registered in Chrome's 'Application' tab.
You need to return a promise from getFiles() in order for the event.waitUntil() to actually wait for the async work. So I recommend returning the promise returned by your promise chain started with caches.open().
Without this its possible the service worker is being terminated before the async work can complete.

Save Facebook credentials on React Native and Firebase

I'm really new to React Native. My intention is that by storing the credentials provided by FBSDK's loginWithReadPermissions, the user won't have to log in each time the app launches, but just one time after it is first installed. Maybe store it somewhere I can check the credentials in componentWillMount().
My first question is: does the FBSDK do this automatically? If not, how can I do this?
I have this code for Facebook Auth:
facebookAuthentication(callback){
LoginManager.logInWithReadPermissions(['public_profile', 'user_likes', 'email']).then(
function(result) {
if (result.isCancelled) {
alert('Inicio de sesiĆ³n cancelado');
} else {
AccessToken.getCurrentAccessToken().then((accessTokenData) =>{
const credential = Firebase.auth.FacebookAuthProvider.credential(accessTokenData.accessToken);
Firebase.auth().signInWithCredential(credential).then((result) =>{
return callback;
}, (error) =>{
console.log('Error en firebase' + error);
});
}, (error) =>{
console.log('ACCESS TOKEN ERROR: ' + error);
});
}
},
function(error) {
console.log('Login failed with error: ' + error);
}
);
}
The code works perfectly, thanks in advance.
With React Native you can use Asyncstorage, which is basically what localstorage is for the web realm: a key-value pair mini-database.
Actually, you can retrieve the currently logged in user using Firebase's firebase.auth().currentUser. Maybe you can check on app startup if it returns a valid user object.

Getting and "Error, wrong validation token" when trying to create a Facebook Chatbot

I'm trying to create a Facebook chatbot with NodeJS, Express, and a Heroku server.
I created my webhook on heroku and had it verified and saved by facebook. I then started adding code that would reply to the incoming messages and I can't seem to get it connected. It keeps saying "Error, wrong validation token" when I try to load my webhook in my browser. And when I try to send my bot a message I get no response. Even though I already had it verified and didn't change the code.
Here is my code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3000;
// body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
// test route
//app.get('/', function (req, res) { res.status(200).send('Hello world!') });
app.get('/', function (req, res) {
if (req.query['hub.verify_token'] === '8FKU9XWeSjnZN4ae') {
res.send(req.query['hub.challenge']);
}
res.send('Error, wrong validation token');
})
app.post('/', function (req, res) {
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));
}
}
res.sendStatus(200);
});
// error handler
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, function () {
console.log('Listening on port ' + port);
});
var token = <myToken>;
function sendTextMessage(sender, text) {
messageData = {
text:text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
So I'm confused as to why nothing is happening and why I'm getting that error. I feel like I'm missing a whole step. I am following this tutorial by the way: https://developers.facebook.com/docs/messenger-platform/quickstart
Any help is appreciated. Thanks!
Edit: Here are my heroku logs
Do not post your full access tokens here!
Have you tested the output of the challenge? Since it's just a GET and you know all values you can try it yourself: your-app-domain.com/your-callback-url?hub_mode=subscribe&hub_verify_token=the_token_you_set_in_your_app_config&hub_challenge=ping which sould print 'ping' if everything work fine.
Make sure you add sendStatus(200) to the hub challenge response, too.
You need to subscribe your page to the app first. To do so make a POST request to /your-page-id/subscribed_apps which should return "success". You can make a GET request to the same endpoint afterwards to double check your app is subscribed to your page
You did not mention which events you subscribed to (needs to be message_deliveries, messages, messaging_optins, messaging_postbacks)
Make sure the webhooks tab in your app dashboard now says "complete"
Test again
You are actually using "request" but you are never importing it anywhere. Here's how to fix it:
var request = require("request")
Once you have added that to your index.js or app.js file (basically whatever this file is), make sure you do:
npm install request --save
This should fix it. Unfortunately, Heroku doesn't error out and say that it does not know what "request" is and that's why it was so hard to figure this out in the first place!

Facebook Open Graph Action coding error

i've been figuring it out for ages, there's no problem debugging tool or in the terminal console, but it keeps popping "error occurred" in the following codes:
<script type="text/javascript">
function postCook()
{
$pageURL = window.location;
FB.api('/me/bgfapp:watch?movie=' + $pageURL,'post',
function(response) {
if (!response || response.error) {
alert('Error Occurred');
} else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
</script>
i tried to echo $pageURL and it returns the current URL successfully, so i can't figure out what's wrong with the above code
updated: 30-Jan-2012
the error says: Error Occurred[object Object][object Object]
You've probably already found a solution but hopefully this will help someone else.
The problem here is that you don't know the names of the child nodes within the response object. If you can't name the specific node then you're going to continually get that error message: "Error occured [Object object] message"
I have a simple workaround that will allow you to see the error message without knowing the names of the response object's child nodes. JSON.stringify will simply convert the entire object into a string, allowing you to view its contents. It won't be pretty but you'll definitely be able to see the error message in there.
Try this:
<script type="text/javascript">
function postCook()
{
$pageURL = window.location;
FB.api('/me/bgfapp:watch?movie=' + $pageURL,'post', function(response) {
if (!response || response.error) {
alert(JSON.stringify(response));
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
An alternate solution would be to output the contents of the response object to the console rather than executing an alert, just replace line 7 in my code sample with this:
console.log(response);
From here, you can open the development console of your web browser and traverse the contents of the response object. Since the console is not always available (phonegap apps for example), the former solution is sometimes more suitable.
Based on your new error message it looks like you need to see what response.error says. Your logic says that either you got no response at all or you got a response.error. You should first figure out what case you are in and act accordingly.
response.responseText and response.error.responseText are undefined because they aren't returned to you.
$pageURL = '/me/bgfapp:watch?movie=' + window.location;
FB.api($pageURL,'post',
function(response) {
if (!response) {
alert('Error Occurred I got no response with ' + $pageURL);
}
else if (response.error) {
alert('Error Occurred '+ response.error);
} else {
alert('Post was successful! Action ID: ' + response.id);
}
});
My suggestion is try simple and work your way up. Debug all variables that you are checking. If you aren't getting a response it could be that your API endpoint call doesn't exist. If you are getting an error then your call is wrong or maybe not authenticated.