Skip to content

Instantly share code, notes, and snippets.

@agronom81
Created February 18, 2021 20:47
Show Gist options
  • Save agronom81/61e7a09cf104c7c548be53d02dd97235 to your computer and use it in GitHub Desktop.
Save agronom81/61e7a09cf104c7c548be53d02dd97235 to your computer and use it in GitHub Desktop.
Fiebase.js
import firebase from "firebase/app";
import "firebase/analytics";
import "firebase/messaging";
import axios from "axios";
let firebaseInit = {
methods: {
firebaseInit: function () {
const firebaseConfig = {
apiKey: "AIzaSyAZW895vVsq-sGPPRm52fQI3V3j6yvylRc",
authDomain: "push-project-e1ffa.firebaseapp.com",
projectId: "push-project-e1ffa",
storageBucket: "push-project-e1ffa.appspot.com",
messagingSenderId: "237926722474",
appId: "1:237926722474:web:46601acb7c7a30e8bc59d3",
measurementId: "G-XQ36BHPE6Y"
};
firebase.initializeApp(firebaseConfig);
if ("Notification" in window && firebase.messaging.isSupported()) {
const messaging = firebase.messaging();
try {
messaging
.getToken({
vapidKey:
"BI-LFBucwec4l41jhP58h9z-HT7KSRzRlh84LSM8LboYSm7ksGCz_Mu4WZQAyPa7ZRMOyIlLy7xcjACK9YSmmVE",
})
.then((currentToken) => {
if (currentToken) {
this.sendTokenToServer(currentToken);
} else {
console.warn("Failed to get token.");
}
})
.catch((err) => {
console.log(
"An error occurred while retrieving token. ",
err
);
this.setTokenSentToServer(false);
});
} catch (e) {
console.log(e);
}
messaging.onMessage((payload) => {
console.log("Message received. firebase.js ", payload);
new Notification(
payload.notification.title,
payload.notification
);
});
}
},
isTokenSentToServer: function (currentToken) {
return (
window.localStorage.getItem("sentFirebaseMessagingToken") ===
currentToken
);
},
setTokenSentToServer: function (currentToken) {
window.localStorage.setItem(
"sentFirebaseMessagingToken",
currentToken ? currentToken : ""
);
},
sendTokenToServer: function (currentToken) {
if (!this.isTokenSentToServer(currentToken)) {
axios
.post("rest/device/token", { token: currentToken })
.then((data) => {
if (data.data.status) {
this.setTokenSentToServer(currentToken);
}
});
}
},
},
};
export default {
firebaseInit,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment