React request location permissions if status denied - javascript

I need some help with one issue on react. The question is how can I enable my geolocation if status denied.
Screenshot
Example how to call or redirect to location settings

create a function to check the permission status and request permission if the status is denied
function getLocation() {
if (navigator.geolocation) {
navigator.permissions.query({name:'geolocation'}).then(permissionStatus => {
if (permissionStatus.state === 'denied') {
alert('Please allow location access.');
window.location.href = "app-settings:location";
} else {
navigator.geolocation.getCurrentPosition(success, error);
}
});
} else {
alert('Geolocation is not supported in your browser.');
}
}

Related

Listen the status of location service with React Native Expo (not permissions)

Imagine that the user is using a map that requires the location to be active, and if not, the map will be closed.
Is there any way to listen to the Location status using Location.hasServicesEnabledAsync()?
Working with:
_getLocationAsync = async () => {
let { status } = await
Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
alert('The request was denied');
}else{
try{
let location = await Location.getCurrentPositionAsync({});
// do something with location
}catch(e){
alert('We could not find your position. Please make sure your
location service provider is on');
console.log('Error while trying to get location: ', e);
}
}
}

Allowed for notification yet permission === 'granted' returns false

I am setting up a Firebase client for JavaScript. When asked for notification permission I allow it, but it still returns false.
firebase.initializeApp(firebaseConfig);
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
//Request permission to receive notifications
messaging.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// ...
} else {
console.log('Unable to get permission to notify.');
}
});
I get the following in my console "Unable to get permission to notify." when I click on allow.
According to the documentation:
The promise resolves if permission is granted. Otherwise, the promise is rejected with an error.
So instead of checking the passed parameter, you should check whether the promise is resolved or rejected:
messaging.requestPermission().then(() => {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// ...
}).catch((err) => {
console.log('Unable to get permission to notify.');
});
That being said, according to the documentation the requestPermission() is deprecated and should be replaced with Notification.requestPermission(). That one looks more the way you tried it:
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// ...
} else {
console.log('Unable to get permission to notify.');
}
});

Facebook not giving permission to access users uploaded photos

Invalid Scopes: user_photos. This message is only shown to developers. Users of your app will ignore these permissions if present. Please read the documentation for valid permissions at: https://developers.facebook.com/docs/facebook-login/permissions
function login( callback ) {
FB.login(function(response) {
if (response.authResponse) {
//console.log('Welcome! Fetching your information.... ');
if (callback) {
callback(response);
}
} else {
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'user_photos'} );
}
https://developers.facebook.com/docs/facebook-login/permissions/#reference-user_photos
This permission is restricted to a limited set of partners and usage requires prior approval by Facebook.

Using chrome push notifications mainfest.json in meteor project

I am following a guide on how to implement the chrome push notification and I am trying to implement it in a Meteor app as a package.
Because I am unable to include the manifest.json I am getting "Registration failed - no sender id provided" or "Registration failed - permission denied". So how can I include this file in my project?
The manifest.json looks like this:
{
"permissions": [ "gcm" ],
"name": "push",
"short_name": "push notification",
"display": "standalone",
"gcm_sender_id": "0000000000000"
}
I have tried including it with the package.js like:
api.addAssets('manifest.json', 'client');
And also put the required variables (gcm_sender_id) in settings.json and starting meteor with meteor --settings settings.json but nothing works.
My service worker registration starts with calling Cpn.serviceWorkerRegistration:
Cpn = {};
Cpn.serviceWorkerRegistration = function () {
console.log("serviceWorkerRegistration called");
subscribe();
console.log(navigator);
// Check that service workers are supported, if so, progressively
// enhance and add push messaging support, otherwise continue without it.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(initialiseState);
} else {
console.warn('Service workers aren\'t supported in this browser.');
}
}
// Once the service worker is registered set the initial state
initialiseState = function () {
console.log("initialiseState");
// Are Notifications supported in the service worker?
if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
console.warn('Notifications aren\'t supported.');
return;
}
// Check the current Notification permission.
// If its denied, it's a permanent block until the
// user changes the permission
if (Notification.permission === 'denied') {
console.warn('The user has blocked notifications.');
return;
}
// Check if push messaging is supported
if (!('PushManager' in window)) {
console.warn('Push messaging isn\'t supported.');
return;
}
// We need the service worker registration to check for a subscription
navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
// Do we already have a push message subscription?
serviceWorkerRegistration.pushManager.getSubscription()
.then(function (subscription) {
if (!subscription) {
return;
}
// Keep your server in sync with the latest subscriptionId
sendSubscriptionToServer(subscription);
})
.catch(function (err) {
console.warn('Error during getSubscription()', err);
});
});
}
function subscribe() {
navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe()
.then(function (subscription) {
// The subscription was successful
// TODO: Send the subscription.endpoint to your server
// and save it to send a push message at a later date
return sendSubscriptionToServer(subscription);
})
.catch(function (e) {
if (Notification.permission === 'denied') {
// The user denied the notification permission which
// means we failed to subscribe and the user will need
// to manually change the notification permission to
// subscribe to push messages
console.warn('Permission for Notifications was denied');
} else {
// A problem occurred with the subscription; common reasons
// include network errors, and lacking gcm_sender_id and/or
// gcm_user_visible_only in the manifest.
console.error('Unable to subscribe to push.', e);
}
});
});
}
And the service worker looks like this:
self.addEventListener('push', showNotification)
self.addEventListener('notificationclick', closeNotificationAndOpenWindow)
function showNotification(event) {
console.log('Received a push message', event)
var title = 'Yay a message.'
var body = 'We have received a push message.'
var icon = '/images/icon-192x192.png'
var tag = 'simple-push-demo-notification-tag'
event.waitUntil(
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
})
)
}
function closeNotificationAndOpenWindow(event) {
console.log('On notification click: ', event.notification.tag)
// Android doesn’t close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close()
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(clients.matchAll({
type: "window"
}).then(function (clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i]
if (client.url == '/' && 'focus' in client)
return client.focus()
}
if (clients.openWindow)
return clients.openWindow('/')
}))
}

Facebook on PhoneGap/Cordova -- File protocol?

Have searched everywhere for this without luck. I'm getting this error when running PhoneGap app on device (works fine in browser):
Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
This is because I haven't added the host to the facebook app configuration. BUT, PhoneGap/Cordova accesses the app through the file:/// protocol, so there's no domain for me to add to Facebook.
Potential options: 1) Figure out how to use a cordova native plugin (this is hard because we're using Parse), 2) Switch Cordova to use localhost instead of file:// (not sure how to do this).
I've been down this road and ultimately went with option #1. Since we're not really dealing with a website there is no domain to add. Cordova needs to use file:// I don't think there is any way around it. The trick with using the plugin is keeping the login status in sync with Parse (use Parse.FacebookUtils.logIn). He's some code that should help you out. This is how I check the login status:
try {
console.log("Trying to get FB login status");
return FB.getLoginStatus(function(response) {
var accessToken, currentView, expDate, facebookAuthData, uid, user;
console.log(response);
if (response.status === "connected") {
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log("Logged in!");
user = Parse.User.current();
if (user != null) {
console.log("we have a user");
} else {
console.log("we don't have a user... need to login with parse");
expDate = new Date(response.authResponse.expirationTime);
facebookAuthData = {
id: response.authResponse.userID + "",
access_token: response.authResponse.accessToken,
expiration_date: expDate.toISOString()
};
Parse.FacebookUtils.logIn(facebookAuthData, {
success: function(_user) {
return console.log("Logged in with Parse!");
},
error: function(error1, error2) {
return console.log("Unable to create/login as Facebook user");
}
});
}
} else {
// not logged in to fb...
}
});
} catch (e) {
return console.log(e);
}
Here's how I handle logins:
return FB.Event.subscribe("auth.authResponseChange", function(response) {
var expDate, facebookAuthData;
if (response.status === "connected") {
console.log(response.status);
try {
expDate = new Date(response.authResponse.expirationTime);
facebookAuthData = {
id: response.authResponse.userID + "",
access_token: response.authResponse.accessToken,
expiration_date: expDate.toISOString()
};
return Parse.FacebookUtils.logIn(facebookAuthData, {
success: function(_user) {
//return window.location.hash = "loginsuccess";
},
error: function(error1, error2) {
console.log("Unable to create/login to as Facebook user");
}
});
} catch (ex) {
return console.log("parse login error " + ex);
}
} else if (response.status === "not_authorized") {
// handle not auth event
} else {
// take them home?
}
});
}

Categories

Resources