使用 Firebase 的 Chrome 擴充功能中的 Google 驗證
我們寫本指南是因為 Google 的官方指南缺少一些重要步驟,我們在下面連結了:
在 Chrome 擴充功能中使用 Firebase 進行驗證
這適用於任何作業系統。出於本指南的目的,我們將使用 Mac OS
先決條件
- Google瀏覽器
- Google 帳號
- Chrome 網路應用商店開發者帳戶(一次性費用 5 美元)
- 已安裝 Node.js 和 npm
第 1 步:建立專案結構
a) 為您的專案建立一個新目錄:
mkdir firebase-chrome-auth cd firebase-chrome-auth
b) 建立兩個子目錄:
mkdir chrome-extension mkdir firebase-project
第 2 步:設定 Firebase 項目
a) 前往 Firebase 控制台。
b)點選「新增項目」並依照步驟建立一個新項目。
c) 建立後,按一下「Web」將 Web 應用程式新增至您的專案。
d) 使用暱稱註冊您的應用程式(例如「Chrome 擴充功能驗證」)。
e) 複製 Firebase 配置物件。稍後你會需要這個。
const firebaseConfig = { apiKey: "example", authDomain: "example.firebaseapp.com", projectId: "example", storageBucket: "example", messagingSenderId: "example", appId: "example" };
f) 導航到 firebase-project 目錄
cd firebase-project
g) 初始化一個新的 npm 項目
npm init -y
h) 安裝 Firebase:
npm 安裝 firebase
i) 在 firebase-project/index.html
中建立一個 index.html 文件
<!DOCTYPE html> <html> <head> <title>Firebase Auth for Chrome Extension</title> </head> <body> <h1>Firebase Auth for Chrome Extension</h1> <script type="module" src="signInWithPopup.js"></script> </body> </html>
j) 在 firebase-project/signInWithPopup.js
中建立一個signInWithPopup.js 文件
import { initializeApp } from 'firebase/app'; import { getAuth, signInWithPopup, GoogleAuthProvider } from 'firebase/auth'; const firebaseConfig = { // Your web app's Firebase configuration // Replace with the config you copied from Firebase Console }; const app = initializeApp(firebaseConfig); const auth = getAuth(); // This gives you a reference to the parent frame, i.e. the offscreen document. const PARENT_FRAME = document.location.ancestorOrigins[0]; const PROVIDER = new GoogleAuthProvider(); function sendResponse(result) { window.parent.postMessage(JSON.stringify(result), PARENT_FRAME); } window.addEventListener('message', function({data}) { if (data.initAuth) { signInWithPopup(auth, PROVIDER) .then(sendResponse) .catch(sendResponse); } });
k) 部署 Firebase 專案
npm install -g firebase-tools firebase login firebase init hosting firebase deploy
請注意部署後提供的託管 URL。 Chrome 擴充功能需要它。
第 3 步:設定 Chrome 擴充功能
a) 導覽至 chrome-extension 目錄
cd ../chrome-extension
b) 在chrome-extension/manifest.json
中建立一個manifest.json文件
{ "manifest_version": 3, "name": "Firebase Auth Extension", "version": "1.0", "description": "Chrome extension with Firebase Authentication", "permissions": [ "identity", "storage", "offscreen" ], "host_permissions": [ "https://*.firebaseapp.com/*" ], "background": { "service_worker": "background.js", "type": "module" }, "action": { "default_popup": "popup.html" }, "web_accessible_resources": [ { "resources": ["offscreen.html"], "matches": ["<all_urls>"] } ], "oauth2": { "client_id": "YOUR-ID.apps.googleusercontent.com", "scopes": [ "openid", "email", "profile" ] }, "key": "-----BEGIN PUBLIC KEY-----\nYOURPUBLICKEY\n-----END PUBLIC KEY-----" }
c) 在 chrome-extension/popup.html
中建立 popup.html 文件
<!DOCTYPE html> <html> <head> <title>Firebase Auth Extension</title> </head> <body> <h1>Firebase Auth Extension</h1> <div id="userInfo"></div> <button id="signInButton">Sign In</button> <button id="signOutButton" style="display:none;">Sign Out</button> <script src="popup.js"></script> </body> </html>
d) 在 chrome-extension/popup.js
中建立 popup.js 文件
document.addEventListener('DOMContentLoaded', function() { const signInButton = document.getElementById('signInButton'); const signOutButton = document.getElementById('signOutButton'); const userInfo = document.getElementById('userInfo'); function updateUI(user) { if (user) { userInfo.textContent = `Signed in as: ${user.email}`; signInButton.style.display = 'none'; signOutButton.style.display = 'block'; } else { userInfo.textContent = 'Not signed in'; signInButton.style.display = 'block'; signOutButton.style.display = 'none'; } } chrome.storage.local.get(['user'], function(result) { updateUI(result.user); }); signInButton.addEventListener('click', function() { chrome.runtime.sendMessage({action: 'signIn'}, function(response) { if (response.user) { updateUI(response.user); } }); }); signOutButton.addEventListener('click', function() { chrome.runtime.sendMessage({action: 'signOut'}, function() { updateUI(null); }); }); });
e) 在chrome-extension/background.js
中建立background.js文件
const OFFSCREEN_DOCUMENT_PATH = 'offscreen.html'; const FIREBASE_HOSTING_URL = 'https://your-project-id.web.app'; // Replace with your Firebase hosting URL let creatingOffscreenDocument; async function hasOffscreenDocument() { const matchedClients = await clients.matchAll(); return matchedClients.some((client) => client.url.endsWith(OFFSCREEN_DOCUMENT_PATH)); } async function setupOffscreenDocument() { if (await hasOffscreenDocument()) return; if (creatingOffscreenDocument) { await creatingOffscreenDocument; } else { creatingOffscreenDocument = chrome.offscreen.createDocument({ url: OFFSCREEN_DOCUMENT_PATH, reasons: [chrome.offscreen.Reason.DOM_SCRAPING], justification: 'Firebase Authentication' }); await creatingOffscreenDocument; creatingOffscreenDocument = null; } } async function getAuthFromOffscreen() { await setupOffscreenDocument(); return new Promise((resolve, reject) => { chrome.runtime.sendMessage({action: 'getAuth', target: 'offscreen'}, (response) => { if (chrome.runtime.lastError) { reject(chrome.runtime.lastError); } else { resolve(response); } }); }); } chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.action === 'signIn') { getAuthFromOffscreen() .then(user => { chrome.storage.local.set({user: user}, () => { sendResponse({user: user}); }); }) .catch(error => { console.error('Authentication error:', error); sendResponse({error: error.message}); }); return true; // Indicates we will send a response asynchronously } else if (message.action === 'signOut') { chrome.storage.local.remove('user', () => { sendResponse(); }); return true; } });
f) 在 chrome-extension/offscreen.html
中建立 offscreen.html 文件
<!DOCTYPE html> <html> <head> <title>Offscreen Document</title> </head> <body> <script src="offscreen.js"></script> </body> </html>
g) 在 _chrome-extension/offscreen.js 中建立一個 offscreen.js 檔案
_
const FIREBASE_HOSTING_URL = 'https://your-project-id.web.app'; // Replace with your Firebase hosting URL const iframe = document.createElement('iframe'); iframe.src = FIREBASE_HOSTING_URL; document.body.appendChild(iframe); chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.action === 'getAuth' && message.target === 'offscreen') { function handleIframeMessage({data}) { try { const parsedData = JSON.parse(data); window.removeEventListener('message', handleIframeMessage); sendResponse(parsedData.user); } catch (e) { console.error('Error parsing iframe message:', e); } } window.addEventListener('message', handleIframeMessage); iframe.contentWindow.postMessage({initAuth: true}, FIREBASE_HOSTING_URL); return true; // Indicates we will send a response asynchronously } });
步驟 4:設定 Firebase 身份驗證
a) 在 Firebase 控制台中,前往「驗證」>登入方法。
b) 啟用 Google 作為登入提供者。
c) 將您的 Chrome 擴充功能 ID 新增至授權網域清單:
格式為:chrome-extension://YOUR_EXTENSION_ID
作為解壓縮的擴充功能載入後,您可以在 Chrome 的擴充功能管理頁面中找到您的擴充功能 ID。
第 5 步:載入並測試擴展
a) 開啟 Google Chrome 並前往 chrome://extensions/。
b) 啟用右上角的「開發者模式」。
c) 點擊「載入解壓縮」並選擇您的 chrome 擴充目錄。
d) 點擊 Chrome 工具列中的擴充功能圖示以開啟彈出視窗。
e) 點選「登入」按鈕並測試驗證流程。
故障排除
如果您遇到 CORS 問題,請確保在 background.js 和 offscreen.js 中正確設定您的 Firebase 託管 URL。
確保您的 Chrome 擴充功能的 ID 已正確新增至 Firebase 的授權網域。
檢查彈出視窗、背景腳本和螢幕外文件中的控制台日誌是否有任何錯誤訊息。
結論
您現在擁有一個 Chrome 擴充程序,它使用 Firebase 驗證和螢幕外文件來處理登入過程。此設定允許安全身份驗證,而無需直接在擴充程式碼中暴露敏感的 Firebase 配置詳細資訊。
請記得在發布擴充功能之前將佔位符值(例如 YOUR_EXTENSION_ID、YOUR-CLIENT-ID、YOUR_PUBLIC_KEY 和 your-project-id)替換為您的實際值。
以上是使用 Firebase 的 Chrome 擴充功能中的 Google 驗證的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。
