Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Firebase云消息传递:getToken()适用于ASP.NET,但VueJs的确切代码失败_Firebase_Vue.js_Firebase Cloud Messaging - Fatal编程技术网

Firebase云消息传递:getToken()适用于ASP.NET,但VueJs的确切代码失败

Firebase云消息传递:getToken()适用于ASP.NET,但VueJs的确切代码失败,firebase,vue.js,firebase-cloud-messaging,Firebase,Vue.js,Firebase Cloud Messaging,我在ASP.NET项目的index.html中有下面的测试代码,它运行良好,获取了令牌。但是,如果复制整个代码并粘贴到新创建的VueJs项目的index.html中,它将失败并出错- “FirebaseError:消息传递:向用户订阅FCM时出现问题:请求缺少所需的身份验证凭据。应为OAuth 2访问令牌、登录cookie或其他有效身份验证凭据。”。 除了index.html之外,我还将firebase-messaging-sw.js和manifest.json复制到该公共文件夹中 我不清楚为什

我在ASP.NET项目的index.html中有下面的测试代码,它运行良好,获取了令牌。但是,如果复制整个代码并粘贴到新创建的VueJs项目的index.html中,它将失败并出错- “FirebaseError:消息传递:向用户订阅FCM时出现问题:请求缺少所需的身份验证凭据。应为OAuth 2访问令牌、登录cookie或其他有效身份验证凭据。”。 除了index.html之外,我还将firebase-messaging-sw.js和manifest.json复制到该公共文件夹中

我不清楚为什么Google希望VueJS项目使用auth令牌,而不是ASP.NET项目使用auth令牌

在调用getToken()之前,我已经花了3天时间搜索了有关如何设置/传递凭据的文档,但没有成功。请让我知道我可能做错了什么。谢谢你的帮助

index.html

Firebase消息传递演示
div{
边缘底部:15px;
}
MsgElem=document.getElementById(“msg”);
TokenElem=document.getElementById(“令牌”);
NotisElem=document.getElementById(“notis”);
ErrElem=document.getElementById(“err”);
//初始化Firebase
//您的web应用程序的Firebase配置
var firebaseConfig={
apiKey:“,
authDomain:“.firebaseapp.com”,
数据库URL:“https://.firebaseio.com",
投射:“,
storageBucket:“.appspot.com”,
messagingSenderId:“”,
appId:“
};
firebase.initializeApp(firebaseConfig);
const messaging=firebase.messaging();
消息传递
.requestPermission()
.然后(函数(){
MsgElem.innerHTML=“已授予通知权限。”;
log(“已授予通知权限”);
//以承诺的形式获得代币
返回消息。getToken()
})
.then(功能(令牌){
TokenElem.innerHTML=“令牌是:”+令牌
})
.catch(函数(err){
ErrElem.innerHTML=ErrElem.innerHTML+“;”+err
log(“无法获得通知权限”,错误);
});
//处理传入的消息。在下列情况下调用:
//-在应用程序具有焦点时收到消息
//-用户单击由服务人员创建的应用程序通知
//`messaging.onBackgroundMessage`处理程序。
messaging.onMessage((有效负载)=>{
log('onMessage.+JSON.stringify(有效负载)中接收的消息);
//更新UI以包含收到的消息。
附加信息(有效载荷);
});
//将消息添加到messages元素。
功能信息(有效负载){
const messagesElement=document.querySelector(“#messages”);
const dataHeaderElement=document.createElement('h5');
const dataElement=document.createElement('pre');
dataElement.style='overflow-x:hidden;';
dataHeaderElement.textContent='收到的消息:';
dataElement.textContent=JSON.stringify(有效负载,null,2);
messagesElement.appendChild(dataHeaderElement);
messagesElement.appendChild(数据元素);
}
//清除所有子项的messages元素。
函数clearMessages(){
const messagesElement=document.querySelector(“#messages”);
while(messagesElement.hasChildNodes()){
messagesElement.removeChild(messagesElement.lastChild);
}
}
函数updateUIForPushEnabled(currentToken){
showHideDiv(tokenDivId,true);
showHideDiv(permissionDivId,false);
showToken(currentToken);
}
函数updateUIForPushPermissionRequired(){
showHideDiv(tokenDivId,false);
showHideDiv(permissionDivId,true);
}
函数showToken(currentToken){
//在控制台和UI中显示令牌。
const tokenElement=document.querySelector(“#token”);
tokenElement.textContent=currentToken;
}
函数resetUI(){
clearMessages();
showToken('加载…');
//获取注册令牌。最初,一旦检索到,将进行网络调用
//对getToken的后续调用将从缓存返回。
messaging.getToken({vapidKey:''})。然后((currentToken)=>{
如果(当前令牌){
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
}否则{
//显示权限请求。
log('没有可用的注册令牌。请求生成令牌的权限');
//显示权限界面。
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch((错误)=>{
console.log('检索令牌时出错',err);
showToken('检索注册令牌时出错',err);
setTokenSentToServer(false);
});
}
//将注册令牌发送到应用程序服务器,以便它可以:
//-将消息发送回此应用
//-从主题订阅/取消订阅令牌
函数sendTokenToServer(currentToken){
如果(!istokensttoserver()){
log('Sending token to server…');
//TODO(开发者):将当前令牌发送到服务器。
setTokenSentToServer(true);
}否则{
console.log('令牌已发送到服务器,因此不会再次发送它'+
<html>
<title>Firebase Messaging Demo</title>
<style>
    div {
        margin-bottom: 15px;
    }
</style>
<body>
    <div id="token"></div>
    <div id="msg"></div>
    <div id="notis"></div>
    <div id="err"></div>
    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/8.2.4/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.2.4/firebase-messaging.js"></script>
    <script>
        MsgElem = document.getElementById("msg");
        TokenElem = document.getElementById("token");
        NotisElem = document.getElementById("notis");
        ErrElem = document.getElementById("err");
        // Initialize Firebase
        // Your web app's Firebase configuration
        var firebaseConfig = {
            apiKey: "<API-KEY>",
            authDomain: "<project>.firebaseapp.com",
            databaseURL: "https://<project>.firebaseio.com",
            projectId: "<projectid>",
            storageBucket: "<project>.appspot.com",
            messagingSenderId: "<senderid>",
            appId: "<appid>"
        };
        firebase.initializeApp(firebaseConfig);

        const messaging = firebase.messaging();
        messaging
            .requestPermission()
            .then(function () {
                MsgElem.innerHTML = "Notification permission granted.";
                console.log("Notification permission granted.");

                // get the token in the form of promise
                return messaging.getToken()
            })
            .then(function (token) {
                TokenElem.innerHTML = "token is : " + token
            })
            .catch(function (err) {
                ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
                console.log("Unable to get permission to notify.", err);
            });

        // Handle incoming messages. Called when:
        // - a message is received while the app has focus
        // - the user clicks on an app notification created by a service worker
        //   `messaging.onBackgroundMessage` handler.
        messaging.onMessage((payload) => {
            console.log('Message received in onMessage. ' + JSON.stringify(payload));
            // Update the UI to include the received message.
            appendMessage(payload);
        });

        // 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);
        }

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

        function resetUI() {
            clearMessages();
            showToken('loading...');
            // Get registration token. Initially this makes a network call, once retrieved
            // subsequent calls to getToken will return from cache.
            messaging.getToken({ vapidKey: '<YOUR_PUBLIC_VAPID_KEY_HERE>' }).then((currentToken) => {
                if (currentToken) {
                    sendTokenToServer(currentToken);
                    updateUIForPushEnabled(currentToken);
                } else {
                    // Show permission request.
                    console.log('No registration 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 registration token. ', err);
                setTokenSentToServer(false);
            });
        }

        // Send the registration 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);
            if (show) {
                div.style = 'display: visible';
            } else {
                div.style = 'display: none';
            }
        }

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

            return self.registration.showNotification(
                notificationTitle,
                notificationOptions,
            );
        });
    </script>
</body>
</html>