Adding a firebase-messaging-sw.js file to Bubble? [UPDATE - file not compatible]

While troubleshooting an error message, I came across a common resolution that suggests adding a firebase-messaging-sw.js file. However, since I am using a bubble HTML element to run the script, I am unsure about the proper way to do this. I attempted using a CDN but I am not confident if it was done correctly or if there is a better approach. Any suggestions?

The error encountered is:

An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: The document is in an invalid state. (messaging/failed-service-worker-registration).
    at registerDefaultSw (registerDefaultSw.ts:43:25)
    at async updateSwReg (updateSwReg.ts:28:5)
    at async getToken$1 (getToken.ts:43:3)

An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: The document is in an invalid state. (messaging/failed-service-worker-registration).

This is how I attempted to add the file:

<script type="importmap">
{
    "imports": {
        "firebase/app": "https://www.gstatic.com/firebasejs/9.6.9/firebase-app.js",
        "firebase/messaging" :"https://www.gstatic.com/firebasejs/9.6.9/firebase-messaging.js"
    }
}
</script>
  <script type="module">
import { initializeApp } from 'firebase/app';
import { getMessaging,getToken } from "firebase/messaging";
const firebaseConfig = {
//my config
}
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);

const swUrl = 'https://3b4293b7c2497062d0307b62bd49f75f.cdn.bubble.io/f1720473376600x761326990998907800/firebase-messaging-sw.js';
const sw = document.createElement('script');
sw.src = swUrl;
document.head.appendChild(sw);

getToken(messaging, {vapidKey: '...myactualvapidkey...'}).then((currentToken) => {
  if (currentToken) {
    console.log(currentToken);
  } else {
    console.log('No registration token available. Request permission to generate one.');
  }
}).catch((err) => {
  console.log('An error occurred while retrieving token. ', err);
});
</script>

It is worth noting that according to this tutorial, the service worker file should remain empty.

I also tried following advice from a similar thread on Stack Overflow. However, I faced import issues when attempting to use the 'firebase/messaging/sw' package.


EDIT

I realized that I could potentially place the file at the root (by navigating to Settings-->SEO/Metatags), but unfortunately, the file does not seem to be recognized. To rectify this issue, I have tried the following code snippet:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/firebase-messaging-sw.js').then(function(registration) {
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

However, the output displays the following error:

ServiceWorker registration failed: DOMException: Failed to register a ServiceWorker: The document is in an invalid state.

Please note that this code is being rendered within an iFrame and the file firebase-messaging-sw.js remains empty.

Answer №1

Important: Please note that this answer is a work in progress and may be incomplete. I am sharing my findings so far in the hope that it might assist others with similar investigations.


<script type="module">
  (async function () {
    // Note: specifically coding for Firebase Web SDK version 10.12.3
    // Note: using direct import() syntax for testing purposes only
    const { initializeApp } = await import("https://www.gstatic.com/firebasejs/10.12.3/firebase-app.js");
    const { getMessaging, getToken } = await import("https://www.gstatic.com/firebasejs/10.12.3/firebase-messaging.js");

    const firebaseConfig = {
      // configuration details here
    }

    const app = initializeApp(firebaseConfig);
    const messaging = getMessaging(app);

    const serviceWorkerRegistration = await window.navigator.serviceWorker.register(
      (location.pathname.startsWith("/version-test") ? "/version-test" : "") + "/firebase-messaging-sw.js",
      {
        scope: "/firebase-cloud-messaging-push-scope"
      }
    );

    // Note: omitted lines where service worker was attached as a script

    try {
      const currentToken = await getToken(messaging, {
        vapidKey: "<VAPID_KEY>",
        serviceWorkerRegistration
      });

      if (currentToken) {
        console.log(currentToken);
      } else {
        console.warn('No registration token available. Request permission to generate one.');
      }
    } catch (err) {
      console.error('An error occurred while retrieving token. ', err);
    }
  })()
    .catch(err => console.error("An unexpected error occurred.", err));
</script>

Note: The default scope value used by the SDK is

"/firebase-cloud-messaging-push-scope"
. More information can be found here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I require displaying the initial three letters of the term "basketball" and then adding dots

Just starting out with CSS and struggling with the flex property. Seems to work fine at larger sizes, but when I reduce the screen size to 320px, I run into issues... Can anyone help me display only the first three letters of "basketball ...

Capture the current state of a page in Next.js

As I develop my Next.js application, I've encountered an architectural challenge. I'm looking to switch between routes while maintaining the state of each page so that I can return without losing any data. While initialProps might work for simple ...

Leverage the power of PHP files within your JavaScript code

I have a PHP file with some calculations that I want to integrate into another JavaScript file. How can I pass variables from JavaScript to perform calculations inside the PHP file? Here is my JavaScript code: $("#upload").on("click", function(){ var ...

How can AngularJS catch the HTML element and data responsible for triggering an error handled by $exceptionHandler?

My application is equipped with a functional $exceptionHandler. It effectively captures angularJS errors and sends the error data to my email for analysis. However, there seems to be an issue where it fails to capture the HTML element responsible for trigg ...

The ::before pseudo element is malfunctioning when used in the makeStyles function

I am currently utilizing the makeStyles function in React, but I seem to be facing an issue where the content within the ::before pseudo-element is not displaying. Strangely enough, when the content is an image it works fine, but text does not render. Jus ...

Replace Ajax Success Function

Looking to customize the behavior of the jQuery ajax function by handling a default action upon successful execution, while still running the callback function specified in the options parameter. Essentially, I need to filter out specific tags from the res ...

Obtain a collection of custom objects through an HTTP GET request to be utilized in an Angular 2 application

I am currently grappling with the task of efficiently retrieving a list of custom objects and displaying their contents using an HTML file. Here is a simplified version of the HTTP GET method that I am working with: [HttpGet("/atr/testing")] public List& ...

When implementing .forEach, an object within the array is mistakenly duplicated

Struggling to populate an array of objects with unique data using the .forEach function to display feedback in the Administrator page of my portfolio. However, encountering an issue where the objects from 'd' are getting duplicated in the 'f ...

Moving Image Progress Indicator

I am currently developing a progress bar animation that is designed to animate from 0 to a specified percentage when the progress bar becomes visible within the browser's viewport. The animation must always trigger when the element is scrolled into vi ...

Secure login verification coupled with intuitive navigation features

Just starting out with react native and I've created a UI for a restaurant app. Now I'm working on converting all static components to dynamic ones. My first task is figuring out how to implement login authentication and then navigate to a specif ...

Ways to organize variables for my specific situation

I need assistance with sorting a list of items alphabetically by name and displaying them on the page. The issue I am facing is that some of the names contain numbers like var items = [ {‘name’ : ‘name 1’}, {‘name’ : ‘name 2’}, ...

Tips for achieving expansion of solely the clicked item and not the whole row

I am trying to create a card that contains a cocktail recipe. The card initially displays just the title, and when you click on a button, it should expand to show the full menu and description. The issue I'm facing is that when I click on one element, ...

From javascript to utilizing ajax calls to interact with php scripts,

I am currently working on a page called edit.php where I need to pass a JavaScript variable to a modal window containing PHP in order to execute a query and retrieve data. Unfortunately, my experience with Ajax is limited and I haven't been able to fi ...

Organizing a collection of clothing sizes with a mix of different measurements using JavaScript

If I have an array like this: $arr = ['xl', 's', '1', '10', '3', 'xs', 'm', '3T', 'xxl', 'xxs', 'one size']; I aim to arrange the array in this o ...

Retrieving data from an API after the onClick event is activated

I'm facing a bit of a challenge with an HTML & JavaScript issue, which I believe should be straightforward to resolve. Since frontend development is not really my forte, I am hoping to find some assistance here. Task: A friend who owns a website buil ...

Implementing global event callback in JavaScript

Is there a way to globally add an `onerror` function for the `div.circle_thumb>img` event? Instead of adding an `onerror` event to each img tag individually, such as shown below. <div class="circle_thumb" ><img src="some/url" onerror="this.sr ...

Express fails to pass password validation

I encountered an issue with a ValidationError stating that the Path password is required while attempting to register a new User. My experience in Node, programming, and authentication is limited. Below is the code for the User model and schema where I ma ...

Detecting a single click versus a drag using RxJS

Currently, I am working with an AngularJS component that needs to respond to both single clicks and drags for resizing purposes. To tackle this problem, I have integrated RxJS (ReactiveX) into my application in search of a suitable solution. The Angular as ...

Experiencing excessive delay in loading data into the DOM following a successful response from a service in AngularJS

I am facing a challenge in loading a large set of data into an HTML table. To begin, you need to click on a button: <a ng-click="get_product()">load data</a> This button triggers a function called get_product: $scope.get_product = func ...

Creating dynamic HTML elements for each section using JavaScript

Is there a way to dynamically add a task (input + label) for each specific section/div when entering the name and pressing the "Add" button? I attempted to create an event for each button to add a task for the corresponding div of that particular section, ...