首页 > 解决方案 > 如何在加载包含 Firebase 的脚本的 Iframe 中使用 Firebase JS SDK?

问题描述

当我尝试在我的 React 应用程序中获取 Firebase 令牌时出现以下错误。

browserErrorMessage: "Failed to register a ServiceWorker: No URL is associated with the caller's document."
code: "messaging/failed-serviceworker-registration"
message: "Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: No URL is associated with the caller's document. (messaging/failed-serviceworker-registration)."

我的应用程序是一个聊天小部件,应该在任何页面中加载。当页面包含我的 javascript 文件时,我的应用程序被加载并创建一个 iframe。在 iframe 中包含另一个脚本,该脚本包含所有聊天小部件代码和 Firebase 库。

索引.html

<!DOCTYPE html>
<html>
  <head>
    <script src="https://example.net/lib.js"></script>
  </head>
  <body>
    <script>
      Lib.init({});
    </script>
  </body>
</html>

lib.js

const div = document.createElement('div');
div.setAttribute('id', Components.ID_DIV);
document.body.appendChild(div);

const iframe = document.createElement('iframe');
iframe.setAttribute('id', Components.ID_FRAME);
iframe.setAttribute('allowFullScreen', '');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('scrolling', 'no');
iframe.className = Components.CLASS_BUTTON;
div.appendChild(iframe);

const iframeDocument = iframe.contentDocument;
iframeDocument.open();
iframeDocument.write(`
  <!DOCTYPE html>
  <html>
    <head>
      <script src="https://example.net/frame.js"></script>
    </head>
    <body/>
  </html>
`);
iframeDocument.close();

框架.js

const config = {
  apiKey: '<API_KEY>',
  projectId: '<PROJECT_ID>',
  messagingSenderId: '<SENDER_ID>',
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.getToken().then((currentToken) => {
  if (currentToken) {
    console.log(currentToken);
  } else {
    messaging.requestPermission().then(() => {
      console.log('Notification permission granted.');
    }).catch((err) => {
      console.log('Unable to get permission to notify.', err);
    });
  }
}).catch((err) => {
  console.log('An error occurred while retrieving token. ', err);
});

Firebase 配置将由客户端提供。
我正在使用 HTTPS 运行所有内容,包括 index.html 页面。
如何让 Firebase 在这种应用程序中工作?

标签: javascriptreactjsfirebasefirebase-cloud-messaging

解决方案


推荐阅读