I'm looking to show different modals to the user to guide them to allow their permission when trying to use a microphone requiring task in my app - based on whether they have not yet been requested for microphone permissions, granted permissions, or blocked permissions.
How can I reliably find out which state of permissions the user is in? Preferably with an onChange handler to know if the user revokes their permission at any point and something that would work for Chrome, Firefox, and Safari.
The inspiration comes from voice.google.com where they show different screen on the call widget when trying to call the Google voice number with the microphone permission set to "ask", "allow", or "block".
I've gone through https://developers.google.com/web/updates/2015/04/permissions-api-for-the-web but I can't seem to find a solution for how I would like to implement this.
Edit:
<div id="button">Click me</div>
<script>
const button = document.getElementById("button")
button.addEventListener('click', () => {
navigator.mediaDevices.getUserMedia({
audio: true
})
.then(function(stream) {
console.log('You let me use your mic!')
console.log(stream)
navigator.permissions.query({
name: 'microphone'
}, ).then(function(permissionStatus) {
console.log("PermissionStatus: ", permissionStatus.state); // granted, denied, prompt
permissionStatus.onchange = function() {
console.log("Permission changed to " + this.state);
}
})
})
.catch(function(err) {
console.error(err)
console.log('No mic for you!')
});
})
navigator.permissions.query({
name: 'microphone'
})
.then(function(permissionStatus) {
console.log("PermissionStatus: ", permissionStatus.state); // granted, denied, prompt
permissionStatus.onchange = function() {
console.log("Permission changed to " + this.state);
}
})
</script>
The name is "microphone" and you'll get "granted", "prompt" or "denied" as the state.
https://developers.google.com/web/fundamentals/media/recording-audio#use_the_permissions_api_to_check_if_you_already_have_access
Related
I want to open permission popup for microphone if microphone permission is not granted,
navigator.permissions.query(
{ name: 'microphone' }
).then(permissionStatus => {
console.log(permissionStatus.state); // granted, denied, prompt
if(permissionStatus.state != 'granted')
{
alert('Please allow your microphone');
}
else
{
this.mic_permission=true;
}
let self=this;
permissionStatus.onchange = function(){
if(this.state!='granted')
{
self.mic_permission=false;
}
console.log("Permission changed to " + this.state);
}
using this code to check whether microphone permission is granted or not but i want to open popup also so that user can allow the microphone permission
My app is requiring that google oauth (via federatedSignIn) be tapped twice in iOS devices, prior to actually signing the user in.
Process:
Upon the first tap, inapp browser opens up and you select which account you're intending to sign in with. Inapp browser closes and seems like all the rest of my logic is not being hit.
Upon the second tap, the inapp browser re-opens up again for a split second (screen is blank), and then closes and THEN the user is actually signed in.
On the iOS simulator/android, however, it seems like it works as expected. Another strange thing is that it works as expected for oauth'ing in with Apple on all devices.
Wondering if anyone else has run into this issue and if y'all have a suggestion?
Where I instantiate the hub listener:
useEffect(() => {
// NOTE: amplify hub listener
const listener = async (data: any) => {
switch (data.payload.event) {
case "signIn":
case "cognitoHostedUI":
await signInUser();
break;
case "signOut":
setUser(null);
break;
default:
break;
}
};
Hub.listen("auth", listener);
}, []);
My google oauth button component:
export function GoogleSignInButton({ title }: GoogleSignInButtonProps) {
return (
<SocialIcon
button
type="google"
title={title}
style={{ padding: 50, marginBottom: 10 }}
onPress={() =>
Auth.federatedSignIn({
provider: "Google" as any,
}).catch(federatedSignInError => {
console.log({ federatedSignInError });
throw new Error(federatedSignInError);
})
}
/>
);
}
I'm also using the react-native-inappbrowser-reborn npm package to have an internal webview when signing in, if that's relevant:
async function urlOpener(url: string, redirectUrl: string) {
await InAppBrowser.isAvailable();
const { type, url: newUrl } = (await InAppBrowser.openAuth(url, redirectUrl, {
showTitle: false,
enableUrlBarHiding: true,
enableDefaultShare: false,
ephemeralWebSession: false,
})) as RedirectResult;
if (type === "success") {
Linking.openURL(newUrl);
}
}
const appsyncAuthenticationTypeOverride = {
...config,
oauth: {
...config.oauth,
urlOpener,
},
aws_appsync_authenticationType: "AWS_IAM",
};
Amplify.configure(appsyncAuthenticationTypeOverride);
i had the same issue.
It seems to be related to Cookies in navigator, you seem to be loading the during the first logging attempt, and using the during the second one.
Also it seems to be sometimes related to redirection errors in Cognito Auth Flow.
I managed to solve it by finding this issue :
https://github.com/aws-amplify/amplify-js/issues/7468
Especially this comment :
https://github.com/aws-amplify/amplify-js/issues/7468#issuecomment-816853703
I am using the following code for checking if my react application has a camera permission:-
checkForCameraPermission = () => {
try {
navigator.permissions.query({ name: 'camera' }).then(permissionStatus => {
// granted, denied, prompt
switch (permissionStatus.state) {
case 'denied':
// eslint-disable-next-line no-alert
// alert(
// 'You need to provide camera permission and reload page to continue futher with KYC journey or else please download the EarlySalary App to continue further.'
// );
this.setState({
cameraDialogStatus: true
});
break;
default:
break;
}
// eslint-disable-next-line no-param-reassign
permissionStatus.onchange = () => {
console.log(`Permission changed to ${this.state}`);
};
});
} catch (error) {
console.log('camera error', error);
// alert('TEST');
this.setState({ isShowTestDialog: true });
}
};
I am using this in component did mount lifecycle method it works fine on most of the browsers but on some browsers it is not supported. So I tried finding out why it wasn't working on some devices and I finally got my answer with the MDN web docs at the following link:-
[https://developer.mozilla.org/en-US/docs/Web/API/Navigator/permissions][1]
Is there a better approach that I can take as my react application is being used on Desktops as well as on mobile phone's and I would like the application to work as expected on all the devices and if not show why it is failing?
Any help or suggestion is much appreciated. Thank you for your time and support.
I'm trying to remove or overwrite my notification signature made by electron.
here is what i get:
I am trying to whether overwrite the signature electron.app.Electron or remove it completely, by knowing
that I have tested it on test mode (npm run start), and also when packed as .exe
also I have noticed that I remove the icon the signature goes a way, but it is very unpleasant without one.
my current notification code is bellow:
function showNotification() {
const notification = new Notification("new message", {
body: "app launched",
icon: __dirname + '/icon.ico',
tag: 'soManyNotification',
hasReply: true
})
}
console.log(Notification.permission)
if (Notification.permission === "granted") {
showNotification()
//alert('we have permission');
} else if (Notification.permission === "denied") {
Notification.requestPermission()
};
any help would be gratefully appreciated ^^
// If this is running on Windows then set UserModelID for notification
if (isWin()) {
app.setAppUserModelId("Proper name to be replaced");
}
When a user clicks...
<%= content_tag(:button, "Send", class: "webpush-button") %>
# Previous Attempt: <%= button_to 'send', class: "webpush-button" %>
<script>
$('.webpush-button').on('click', (e) => {
navigator.serviceWorker.ready
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((subscription) => {
$.post("/post", {
subscription: subscription.toJSON(),
message: 'You clicked a button!'
});
});
});
});
</script>
he should be taken through...
class PushNotificationsController < ApplicationController
def push
Webpush.payload_send(
message: params[:message],
endpoint: params[:subscription][:endpoint],
p256dh: params[:subscription][:keys][:p256dh],
auth: params[:subscription][:keys][:auth],
vapid: {
subject: "mailto:sender#example.com",
public_key: ENV['VAPID_PUBLIC_KEY'],
private_key: ENV['VAPID_PRIVATE_KEY']
}
)
end
end
but instead nothing happens. The .webpush-button javascript never kicks in. I put it in two places and it still has no effect...
application.js
/ Register the serviceWorker script at /serviceworker.js from our server if supported
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/serviceworker.js').then(function(reg) {
console.log('Service worker change, registered the service worker');
});
}
// Otherwise, no push notifications :(
else {
console.error('Service worker is not supported in this browser');
}
// When serviceWorker is supported, installed, and activated,
// subscribe the pushManager property with the vapidPublicKey
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: window.vapidPublicKey
});
});
$('.webpush-button').on('click', (e) => {
navigator.serviceWorker.ready
.then((serviceWorkerRegistration) => {
serviceWorkerRegistration.pushManager.getSubscription()
.then((subscription) => {
$.post('/push', {
subscription: subscription.toJSON(),
message: 'You clicked a button!'
});
});
});
});
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
console.error("This browser does not support desktop notification");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
console.log("Permission to receive notifications has been granted");
}
// Otherwise, we need to ask the user for permission
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
console.log("Permission to receive notifications has been granted");
}
});
}
application.html.erb
<script>
window.vapidPublicKey = new Uint8Array("<%= #decodedVapidPublicKey %>");
</script>
Now based on the tutorial and git code I used... the subscription should be gathered from the serviceworker so then why am I still getting a nil error?
I'm using serviceworker & webpush gems and followed this VAPID tutorial.
Not a duplicate. The other question is focused on params. This one is focused on javascript not triggering.
First, you should only put the javascript at one place.
Second, add the .webpush-button click method after page be ready
$(document).on('ready page:load', function () {
});
And in the chrome dev tools, Tab Event Listeners, check if the html element has click event.