消息传递:未授予和阻止通知权限

保罗

https服务器中的Firebase消息传递错误。

An error occurred while retrieving token. FirebaseError: Messaging: The notification permission was not granted and blocked instead. (messaging/permission-blocked).

我应该怎么做才能获得我的令牌?在本地主机上,它正在工作。

这是我的代码:

firebase-messaging-sw.js

// Import and configure the Firebase SDK
// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
importScripts("https://www.gstatic.com/firebasejs/7.8.1/firebase-app.js")
importScripts("https://www.gstatic.com/firebasejs/7.8.1/firebase-messaging.js")


// Your web app's Firebase configuration
var firebaseConfig = {
  apiKey: apiKey,
  authDomain: authDomain,
  databaseURL: databaseURL,
  projectId: projectId,
  storageBucket: storageBucket,
  messagingSenderId: messagingSenderId,
  appId: appId,
  measurementId: measurementId
};


// Initialize Firebase
firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();
/**
 * Here is is the code snippet to initialize Firebase Messaging in the Service
 * Worker when your app is not hosted on Firebase Hosting.
 // [START initialize_firebase_in_sw]
 // Give the service worker access to Firebase Messaging.
 // Note that you can only use Firebase Messaging here, other Firebase libraries
 // are not available in the service worker.
 importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
 importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
 // Initialize the Firebase app in the service worker by passing in the
 // messagingSenderId.
 firebase.initializeApp({
   'messagingSenderId': 'YOUR-SENDER-ID'
 });
 // Retrieve an instance of Firebase Messaging so that it can handle background
 // messages.
 const messaging = firebase.messaging();
 // [END initialize_firebase_in_sw]
 **/

// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]

// [END background_handler]

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  var notificationTitle = 'Background Message Title';
  var notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});

footer.blade.php 在// script //部分:

  // Your web app's Firebase configuration
  var firebaseConfig = {
     apiKey: apiKey,
  authDomain: authDomain,
  databaseURL: databaseURL,
  projectId: projectId,
  storageBucket: storageBucket,
  messagingSenderId: messagingSenderId,
  appId: appId,
  measurementId: measurementId
  };

  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

  const tokenDivId = 'token_div';
  const permissionDivId = 'permission_div';

  const messaging = firebase.messaging();

  messaging.usePublicVapidKey('BKotWNDl7JOuYb-UeusSlSl47onAFH9sWJ_M1WDivsjWq0AZWah5LjVfBAxbcS8T8Yo10HEw_xPX68kMnzTQC2k');

  // Get Instance ID token. Initially this makes a network call, once retrieved
  // subsequent calls to getToken will return from cache.
  messaging.getToken().then((currentToken) => {
    if (currentToken) {

      sendTokenToServer(currentToken);
      updateUIForPushEnabled(currentToken);
    } else {
      // Show permission request.
      console.log('No Instance ID token available. Request permission to generate one.');
      // Show permission UI.
      updateUIForPushPermissionRequired();
      setTokenSentToServer(false);
    }
  }).catch((err) => {
    console.log('An error occurred while retrieving token. ', err);
    showToken('Error retrieving Instance ID token. ', err);
    setTokenSentToServer(false);
  });

  // Callback fired if Instance ID token is updated.
  messaging.onTokenRefresh(() => {
    messaging.getToken().then((refreshedToken) => {
      console.log('Token refreshed.');
      // Indicate that the new Instance ID token has not yet been sent to the
      // app server.
      setTokenSentToServer(false);
      // Send Instance ID token to app server.
      sendTokenToServer(refreshedToken);
      // ...
    }).catch((err) => {
      console.log('Unable to retrieve refreshed token ', err);
      showToken('Unable to retrieve refreshed token ', err);
    });
  });

  function resetUI() {
    clearMessages();
    showToken('loading...');
    // [START get_token]
    // Get Instance ID token. Initially this makes a network call, once retrieved
    // subsequent calls to getToken will return from cache.
    messaging.getToken().then(function(currentToken) {
      if (currentToken) {
        sendTokenToServer(currentToken);
        updateUIForPushEnabled(currentToken);
      } else {
        // Show permission request.
        console.log('No Instance ID token available. Request permission to generate one.');
        // Show permission UI.
        updateUIForPushPermissionRequired();
        setTokenSentToServer(false);
      }
    }).catch(function(err) {
      console.log('An error occurred while retrieving token. ', err);
      showToken('Error retrieving Instance ID token. ', err);
      setTokenSentToServer(false);
    });
    // [END get_token]


  }


  function showToken(currentToken) {
    // Show token in console and UI.
    var tokenElement = document.querySelector('#token');
    tokenElement.textContent = currentToken;
  }

  // Send the Instance ID token your application server, so that it can:
  // - send messages back to this app
  // - subscribe/unsubscribe the token from topics
  function sendTokenToServer(currentToken) {
    if (!isTokenSentToServer()) {
      console.log('Sending token to server...');
      // TODO(developer): Send the current token to your server.
      setTokenSentToServer(true);
    } else {
      console.log('Token already sent to server so won\'t send it again ' +
          'unless it changes');
    }

  }

  function isTokenSentToServer() {
    return window.localStorage.getItem('sentToServer') === '1';
  }

  function setTokenSentToServer(sent) {
    window.localStorage.setItem('sentToServer', sent ? '1' : '0');
  }

  function showHideDiv(divId, show) {
    const div = document.querySelector('#' + divId);
  }

  function requestPermission() {
    console.log('Requesting permission...');
    // [START request_permission]
    messaging.requestPermission().then(function() {
      console.log('Notification permission granted.');
      // TODO(developer): Retrieve an Instance ID token for use with FCM.
      // [START_EXCLUDE]
      // In many cases once an app has been granted notification permission, it
      // should update its UI reflecting this.
      resetUI();
      // [END_EXCLUDE]
    }).catch(function(err) {
      console.log('Unable to get permission to notify.', err);
    });
    // [END request_permission]
  }

  function deleteToken() {
    // Delete Instance ID token.
    // [START delete_token]
    messaging.getToken().then(function(currentToken) {
      messaging.deleteToken(currentToken).then(function() {
        console.log('Token deleted.');
        setTokenSentToServer(false);
        // [START_EXCLUDE]
        // Once token is deleted update UI.
        resetUI();
        // [END_EXCLUDE]
      }).catch(function(err) {
        console.log('Unable to delete token. ', err);
      });
      // [END delete_token]
    }).catch(function(err) {
      console.log('Error retrieving Instance ID token. ', err);
      showToken('Error retrieving Instance ID token. ', err);
    });

  }

  // Add a message to the messages element.
  function appendMessage(payload) {
    const messagesElement = document.querySelector('#messages');
    const dataHeaderELement = document.createElement('h5');
    const dataElement = document.createElement('pre');
    dataElement.style = 'overflow-x:hidden;';
    dataHeaderELement.textContent = 'Received message:';
    dataElement.textContent = JSON.stringify(payload, null, 2);
    messagesElement.appendChild(dataHeaderELement);
    messagesElement.appendChild(dataElement);
  }

  // Clear the messages element of all children.
  function clearMessages() {
    const messagesElement = document.querySelector('#messages');
    while (messagesElement.hasChildNodes()) {
      messagesElement.removeChild(messagesElement.lastChild);
    }
  }

  function updateUIForPushEnabled(currentToken) {
    showHideDiv(tokenDivId, true);
    showHideDiv(permissionDivId, false);
    showToken(currentToken);
  }

  function updateUIForPushPermissionRequired() {
    showHideDiv(tokenDivId, false);
    showHideDiv(permissionDivId, true);
  }
迈克尔·布莱利

这表明您已阻止已部署网站上的推送通知权限。messaging.getToken()可能是错误的(有关更多信息,请参阅文档)。

如果您使用的是Chrome浏览器,则应该可以单击URL左侧的锁,然后转到“网站设置”,在该网站上您会看到一个带有网站通知设置的响铃图标:

Chrome通知设置的屏幕截图

可以将其设置为“阻止”,而您需要将其更改为“允许”。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Android推送通知,未授予权限

来自分类Dev

未授予Android权限

来自分类Dev

未授予Android权限

来自分类Dev

Firebase和推送通知/云消息传递

来自分类Dev

检测何时询问并授予对iOS通知的权限?

来自分类Dev

Android Q RecoverableSecurityException未授予访问权限

来自分类Dev

sshd AllowGroups组未授予访问权限

来自分类Dev

反应本机Firebase 6云消息传递和推送通知

来自分类Dev

Akka消息未传递

来自分类Dev

检查是否已授予通知权限(Xamarin,iOS)

来自分类Dev

如何为未提升权限的用户授予Windows特权?

来自分类Dev

SQL Server:存储过程的EXECUTE AS子句未授予sysadmin权限

来自分类Dev

棉花糖android的“写入设置”权限未授予

来自分类Dev

Sitecore ItemWebApi-“未授予对网站的访问权限”

来自分类Dev

SQL Server:存储过程的EXECUTE AS子句未授予sysadmin权限

来自分类Dev

INJECT_EVENTS 权限未授予特权应用

来自分类Dev

Facebook 未授予访问用户上传照片的权限

来自分类Dev

使用 Google Apps 脚本时 OAuth 未授予访问权限

来自分类Dev

向目录授予“ rwx”权限,但不希望用户授予mkdir和touch权限

来自分类Dev

Linux错误消息:授予所有权限后,权限被拒绝

来自分类Dev

使用php的iOS的苹果推送通知和android的google cloud消息传递?

来自分类Dev

Firebase云消息传递和Firebase通知之间有什么区别?

来自分类Dev

CPU 和带宽密集型是否直接使用 Firebase 云消息传递发送推送通知?

来自分类Dev

如何使用 fcm(firebase 云消息传递)和 Scala Play 框架发送通知?

来自分类Dev

消息通知和提取内容

来自分类Dev

Flutter 云消息和通知

来自分类Dev

MySQL创建用户和授予权限脚本

来自分类Dev

如何为群组和管理员授予权限

来自分类Dev

MySQL创建用户和授予权限脚本

Related 相关文章

  1. 1

    Android推送通知,未授予权限

  2. 2

    未授予Android权限

  3. 3

    未授予Android权限

  4. 4

    Firebase和推送通知/云消息传递

  5. 5

    检测何时询问并授予对iOS通知的权限?

  6. 6

    Android Q RecoverableSecurityException未授予访问权限

  7. 7

    sshd AllowGroups组未授予访问权限

  8. 8

    反应本机Firebase 6云消息传递和推送通知

  9. 9

    Akka消息未传递

  10. 10

    检查是否已授予通知权限(Xamarin,iOS)

  11. 11

    如何为未提升权限的用户授予Windows特权?

  12. 12

    SQL Server:存储过程的EXECUTE AS子句未授予sysadmin权限

  13. 13

    棉花糖android的“写入设置”权限未授予

  14. 14

    Sitecore ItemWebApi-“未授予对网站的访问权限”

  15. 15

    SQL Server:存储过程的EXECUTE AS子句未授予sysadmin权限

  16. 16

    INJECT_EVENTS 权限未授予特权应用

  17. 17

    Facebook 未授予访问用户上传照片的权限

  18. 18

    使用 Google Apps 脚本时 OAuth 未授予访问权限

  19. 19

    向目录授予“ rwx”权限,但不希望用户授予mkdir和touch权限

  20. 20

    Linux错误消息:授予所有权限后,权限被拒绝

  21. 21

    使用php的iOS的苹果推送通知和android的google cloud消息传递?

  22. 22

    Firebase云消息传递和Firebase通知之间有什么区别?

  23. 23

    CPU 和带宽密集型是否直接使用 Firebase 云消息传递发送推送通知?

  24. 24

    如何使用 fcm(firebase 云消息传递)和 Scala Play 框架发送通知?

  25. 25

    消息通知和提取内容

  26. 26

    Flutter 云消息和通知

  27. 27

    MySQL创建用户和授予权限脚本

  28. 28

    如何为群组和管理员授予权限

  29. 29

    MySQL创建用户和授予权限脚本

热门标签

归档