Chrome扩展中使用signInWithPopup登录时遇脚本加载拒绝问题
Chrome扩展中signInWithPopup加载脚本错误的解决方案
出现"Refused to load the script"错误,核心原因是Chrome扩展的**内容安全策略(CSP)**限制了外部脚本加载,同时可能缺少必要的权限或OAuth配置。以下是具体修复步骤:
1. 调整内容安全策略(CSP)
在manifest.json中更新CSP规则,允许加载Google认证相关的脚本和嵌入窗口:
// 适用于Manifest V3 "content_security_policy": { "extension_pages": "script-src 'self' https://accounts.google.com; object-src 'self'; frame-src https://accounts.google.com;" } // 适用于Manifest V2 "content_security_policy": "script-src 'self' https://accounts.google.com; object-src 'self'; frame-src https://accounts.google.com;"
2. 添加必要权限
在manifest.json中声明identity权限和Google认证的主机权限:
"permissions": ["identity"], "host_permissions": ["https://accounts.google.com/*"]
3. 配置OAuth客户端ID
Chrome扩展需要绑定正确的OAuth客户端ID才能正常使用Google登录:
- 登录Google Cloud控制台,创建Chrome应用类型的OAuth客户端ID,填写你的扩展ID作为授权来源
- 在
manifest.json中添加OAuth配置:
"oauth2": { "client_id": "你的客户端ID.apps.googleusercontent.com", "scopes": ["openid", "email", "profile"] }
4. 代码适配(可选)
如果仍有问题,可尝试通过Chrome的identity.launchWebAuthFlowAPI配合Firebase完成登录,替代signInWithPopup:
const signInWithGoogle = async () => { try { const authUrl = 'https://accounts.google.com/o/oauth2/v2/auth?' + new URLSearchParams({ client_id: '你的客户端ID.apps.googleusercontent.com', response_type: 'id_token', scope: 'openid email profile', redirect_uri: chrome.identity.getRedirectURL(), nonce: Math.random().toString(36).substring(2) }); const redirectUrl = await chrome.identity.launchWebAuthFlow({ url: authUrl, interactive: true }); const idToken = new URL(redirectUrl).hash.match(/id_token=([^&]+)/)[1]; // 将idToken传给Firebase完成认证 const credential = GoogleAuthProvider.credential(idToken); const result = await signInWithCredential(auth, credential); console.log(result.user); } catch (error) { console.error(error); } };
内容的提问来源于stack exchange,提问作者james akpan
相关产品推荐
相关产品推荐

