javascript - 带有清单 v3 纯 JavaScript 的 firebase “Sign-in-with-Google”
问题描述
我正在尝试编写一个使用 firebase 身份验证的 chrome 扩展,特别是 Google 登录。
我的第一次尝试是在 popup.js 中加载所有必要的 firebase 代码,比如
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js';
import { getAuth, onAuthStateChanged, connectAuthEmulator,signOut,signInWithEmailAndPassword, GoogleAuthProvider,signInWithPopup } from 'https://www.gstatic.com/firebasejs/9.0.1/firebase-auth.js';
import { getFirestore, setDoc, getDoc, collection, doc, connectFirestoreEmulator, query, where, getDocs } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-firestore.js";
const firebaseApp = initializeApp({
apiKey: "xxx",
authDomain: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxx"
});
const auth = getAuth(firebaseApp);
const provider = new GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
provider.setCustomParameters({
'login_hint': 'xxx@gmail.com'
});
onAuthStateChanged(auth, user => {
if (user) {
console.log('Logged in as ${user.email}' );
} else {
console.log('No user');
}
});
connectAuthEmulator(auth, "http://localhost:9099");
var db = getFirestore(firebaseApp);
connectFirestoreEmulator(db, 'localhost', 8080);
...
signInWithPopup(auth, provider)
.then((result) => {
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
const user = result.user;
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const credential = GoogleAuthProvider.credentialFromError(error);
});
...
但这在 manifest v3 中不起作用,因为扩展页面不能像这样加载“不安全”脚本。
所以我想,好吧,让我们通过消息传递在后台页面中执行此操作,并在清单中定义它:
...
"background": {
"service_worker": "background.js",
"type" : "module"
},
...
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'",
"sandbox": "sandbox allow-scripts; script-src 'self' 'https://apis.google.com/' 'https://www.gstatic.com/' 'https://*.firebaseio.com' 'https://www.googleapis.com' 'https://ajax.googleapis.com'; object-src 'self'"
},
...
但是,当加载 background.js 时,我会收到有关未定义窗口的错误:
Uncaught ReferenceError: window is not defined
https://www.gstatic.com/firebasejs/9.0.1/firebase-auth.js
Stack Trace
https://www.gstatic.com/firebasejs/9.0.1/firebase-auth.js:6913 (anonymous function)
这是有道理的,因为后台窗口真的没有窗口,我只使用后台脚本来登录和注销。但我知道一个窗口可能用于谷歌登录,因为用户需要一个弹出窗口来选择要使用的帐户。
所以,我似乎被困住了。在 manifest v3 中是否不可能通过 firebase 进行 Google 登录?
如果是这样,有人可以指点一下吗?
非常感谢!
解决方案
推荐阅读
- java - 如何根据关键字段之一在 Java 中合并地图?
- python - Visual Studio 代码:设置容器时出错
- python - 是否有可能用 Python 修复 CSV 逗号问题?
- drake - 如何搜索指南针步态限制周期?
- c# - 分割矩形进行二进制空间分区,不知道如何定位它们
- user-interface - 在 Flutter 上使用 ChangeNotifierProvider 选择另一个选项卡时如何更改 AppBar 颜色?
- python - mysql - django - android的最佳模型是什么?
- django - 多步形式中的 CRUD 操作
- django - Django massmailer - TemplateDoesNotExist
- maven - 从 Jenkins 部署到 mule 服务器期间的问题