I would like to call a function which is defined inside src/App.js (callMe) from public folder,
In App.js
import messaging from './firebase-init';
import './App.css';
function App () {
function callMe() {
console.log('Call me function called');
}
return (
<div className="App">
<h1>Hello World</h1>
</div>
);
}
export default App;
And I've another file firebase-messaging-sw.js located inside public folder,
In firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js');
self.addEventListener('notificationclick', function (event) {
console.log('On notification click: ', event);
event.notification.close();
event.waitUntil(clients.matchAll({
includeUncontrolled: true,
type: "window",
}).then(function (clientList) {
console.log('********* clientList: ', clientList);
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url !== '' && 'focus' in client) {
client.focus();
callMe(); // This function is defined in src/App.js
break;
}
}
}));
});
const firebaseConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize Firebase
const initializedFirebaseApp = firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
Can you please help me, how should I call function callMe() ?
You can try to use postMessage
window.postMessage spec
simply send Message in your .js file
window.postMessage('someFunctionId','*')
and then in react you can add eventListener for this message (best solution is in useEffect and dont forget to removeListener on callback)
useEffect(()=>{
window.addEventListener("message",handlerFunc);
return ()=> window.removeEventListener("message",handlerFunc);
}
and ind your handlerFunc you can just check if message is the same as your ID as you posted...
you can even pass object instad of string to pass some parameters for your function
window.postMessage({id:'someFunctionId',data:'test'},'*');