javascript - 如何在加载包含 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 在这种应用程序中工作?
解决方案
推荐阅读
- javascript - 典型的 HTTP 会话,但 Ajax 风格
- c# - Xamarin 形式。如何绑定选择器的选定项目以在切换视图时显示在选择器字段中?
- javascript - JavaScript fetch() - 将 ReadableStreams 数组映射到数组
- netlogo - Netlogo:通过滑块输入概率
- big-o - 试图理解这个 big0 符号的复杂性
- python - 生成与任意维度上的一组其他向量正交的向量
- c++ - 如何通过指定的行和列获取 Clang AST 节点?
- python - Reportlab,如何更改页面方向?
- python - 在张量流中逐元素地从两个张量中获取更高的值
- r - 使用 styler 设置 R 代码样式时,使用 = 而不是 <- 进行赋值