【发布时间】:2020-12-08 15:48:18
【问题描述】:
我尝试在我的 REact js 项目中使用 firebase 实现网络推送通知。
Index.js
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import './App.css';
import { createStore, compose, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension/developmentOnly";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import {messaging} from "./config/FirebaseConfig"
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import rootReducer from "./reducers/rootReducer";
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(thunk))
);
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register(`./firebase-messaging-sw.js`)
.then(function(registration) {
messaging.useServiceWorker(registration);
console.log("Registration successful, scope is:", registration.scope);
})
.catch(function(err) {
console.log("Service worker registration failed, error:", err);
});
}
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
serviceWorker.register();
以上文件是位于 src 文件夹中的主要源文件。 我添加了 firebase-messaging-sw.js,如下所示:
importScripts("https://www.gstatic.com/firebasejs/5.9.4/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/5.9.4/firebase-messaging.js");
firebase.initializeApp({
messagingSenderId: "XXXXXX",
});
const messaging = firebase.messaging();
messaging.usePublicVapidKey("XXXXXXXXXXXXXXXXXXXXX")
messaging.setBackgroundMessageHandler(function(payload) {
const promiseChain = clients
.matchAll({
type: "window",
includeUncontrolled: true
})
.then(windowClients => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
windowClient.postMessage(payload);
}
})
.then(() => {
return registration.showNotification("my notification title");
});
return promiseChain;
});
self.addEventListener('notificationclick', function(event) {
// do what you want
// ...
});
我在 Main 组件的 amount 方法上添加了请求权限代码,如下所示:
componentDidMount()
{
messaging.requestPermission()
.then(async function() {
const token = await messaging.getToken();
console.log("token", token)
})
.catch(function(err) {
console.log("d to get permission to notify.", err);
});
navigator.serviceWorker.addEventListener("message", (message) => console.log(message));
messaging.onMessage((payload) => console.log('Message received. ', payload));
const fetchOptions = {
method: "POST",
headers: {
"Authorization": "key=l9oalOyzXcU-NqCI4LZyVrLuF3X3_4tiOHpMUYK_AxC4G...",
"Content-Type": "application/json"
},
body: JSON.stringify({
to:"e56_nKx5Ejm1HyWHKcvZFq:APA91bH-...-nKE9YEILYu7RQBBiyCs_CUo2IC0DX-87cMgmMcYwvYQ1yg0BmqWfAgbbkfPtfzXGGOdzmvxVX2wBlwhnnK5oUxjtXalQ4T5CM7IQOhertbXc",
notification : {
"title": "Message recieived from:",
"body": message,
"click_action": "http://localhost:3000/",
"icon": "http://url-to-an-icon/icon.png"
},
})
}
fetch("https://fcm.googleapis.com/fcm/send", fetchOptions)
.then(response =>console.log(response))
.then(data => console.log(data));
}
同时添加 serviceWorker.js 文件的代码,该文件在 index.js 文件中使用
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more,'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
我在端口 3000 上运行应用程序,我可以看到 google chrome 会抛出如下错误:
Service Worker 注册失败。我不知道我做错了什么。
您能帮我解决这个问题吗?另外,如果您需要我的其他任何东西,请告诉我。
【问题讨论】:
标签: reactjs firebase push-notification react-redux