j) Create a signInWithPopup.js file in firebase-project/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) Deploy the Firebase project

npm install -g firebase-toolsfirebase loginfirebase init hostingfirebase deploy

Note the hosting URL provided after deployment. You\\'ll need this for the Chrome extension.

Step 3: Set up the Chrome Extension

a) Navigate to the chrome-extension directory
cd ../chrome-extension

b) Create a manifest.json file in chrome-extension/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\\\": [\\\"\\\"]    }  ],  \\\"oauth2\\\": {    \\\"client_id\\\": \\\"YOUR-ID.apps.googleusercontent.com\\\",    \\\"scopes\\\": [      \\\"openid\\\",       \\\"email\\\",       \\\"profile\\\"    ]  },  \\\"key\\\": \\\"-----BEGIN PUBLIC KEY-----\\\\nYOURPUBLICKEY\\\\n-----END PUBLIC KEY-----\\\"}

c) Create a popup.html file in chrome-extension/popup.html

    Firebase Auth Extension    

Firebase Auth Extension

d) Create a popup.js file in chrome-extension/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) Create a background.js file in chrome-extension/background.js

const OFFSCREEN_DOCUMENT_PATH = \\'offscreen.html\\';const FIREBASE_HOSTING_URL = \\'https://your-project-id.web.app\\'; // Replace with your Firebase hosting URLlet 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) Create an offscreen.html file in chrome-extension/offscreen.html

    Offscreen Document    

g) Create an offscreen.js file in _chrome-extension/offscreen.js
_

const FIREBASE_HOSTING_URL = \\'https://your-project-id.web.app\\'; // Replace with your Firebase hosting URLconst 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    }});

Step 4: Configure Firebase Authentication

a) In the Firebase Console, go to Authentication > Sign-in method.
b) Enable Google as a sign-in provider.
c) Add your Chrome extension\\'s ID to the authorized domains list:
The format is: chrome-extension://YOUR_EXTENSION_ID
You can find your extension ID in Chrome\\'s extension management page after loading it as an unpacked extension.

Step 5: Load and Test the Extension

a) Open Google Chrome and go to chrome://extensions/.
b) Enable \\\"Developer mode\\\" in the top right corner.
c) Click \\\"Load unpacked\\\" and select your chrome-extension directory.
d) Click on the extension icon in Chrome\\'s toolbar to open the popup.
e) Click the \\\"Sign In\\\" button and test the authentication flow.

Troubleshooting

If you encounter CORS issues, ensure your Firebase hosting URL is correctly set in both background.js and offscreen.js.

Make sure your Chrome extension\\'s ID is correctly added to Firebase\\'s authorized domains.

Check the console logs in the popup, background script, and offscreen document for any error messages.

Conclusion

You now have a Chrome extension that uses Firebase Authentication with an offscreen document to handle the sign-in process. This setup allows for secure authentication without exposing sensitive Firebase configuration details directly in the extension code.

Remember to replace placeholder values (like YOUR_EXTENSION_ID, YOUR-CLIENT-ID, YOUR_PUBLIC_KEY, and your-project-id) with your actual values before publishing your extension.

","image":"http://www.luping.net/uploads/20241006/172820052667023f4e031a4.jpg","datePublished":"2024-11-02T15:11:01+08:00","dateModified":"2024-11-02T15:11:01+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 Firebase 的 Chrome 扩展程序中的 Google 身份验证

使用 Firebase 的 Chrome 扩展程序中的 Google 身份验证

发布于2024-11-02
浏览:534

Google Authentication in a Chrome Extension with Firebase

We're writing this guide because the official guide by Google is missing a few important steps, we've linked in below:

Authenticate with Firebase in a Chrome extension

This will work on any operating system. For the purposes of this guide we'll be using Mac OS

Prerequisites

  • Google Chrome browser
  • A Google account
  • A Chrome web store developer account ($5 one time fee)
  • Node.js and npm installed

Step 1: Create the Project Structure

a) Create a new directory for your project:

mkdir firebase-chrome-auth
cd firebase-chrome-auth

b) Create two subdirectories:

mkdir chrome-extension
mkdir firebase-project

Step 2: Set up the Firebase Project

a) Go to the Firebase Console.
b) Click "Add project" and follow the steps to create a new project.
c) Once created, click on "Web" to add a web app to your project.
d) Register your app with a nickname (e.g., "Chrome Extension Auth").
e) Copy the Firebase configuration object. You'll need this later.

const firebaseConfig = {
  apiKey: "example",
  authDomain: "example.firebaseapp.com",
  projectId: "example",
  storageBucket: "example",
  messagingSenderId: "example",
  appId: "example"
};

f) Navigate to the firebase-project directory
cd firebase-project
g) Initialize a new npm project
npm init -y
h) Install Firebase:
npm install firebase
i) Create an index.html file in firebase-project/index.html


 
  Firebase Auth for Chrome Extension
 
 
  

Firebase Auth for Chrome Extension

j) Create a signInWithPopup.js file in firebase-project/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) Deploy the Firebase project

npm install -g firebase-tools
firebase login
firebase init hosting
firebase deploy

Note the hosting URL provided after deployment. You'll need this for the Chrome extension.

Step 3: Set up the Chrome Extension

a) Navigate to the chrome-extension directory
cd ../chrome-extension

b) Create a manifest.json file in chrome-extension/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": [""]
    }
  ],
  "oauth2": {
    "client_id": "YOUR-ID.apps.googleusercontent.com",
    "scopes": [
      "openid", 
      "email", 
      "profile"
    ]
  },
  "key": "-----BEGIN PUBLIC KEY-----\nYOURPUBLICKEY\n-----END PUBLIC KEY-----"
}

c) Create a popup.html file in chrome-extension/popup.html



    Firebase Auth Extension


    

Firebase Auth Extension

d) Create a popup.js file in chrome-extension/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) Create a background.js file in chrome-extension/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) Create an offscreen.html file in chrome-extension/offscreen.html



    Offscreen Document


    


g) Create an offscreen.js file in _chrome-extension/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
    }
});

Step 4: Configure Firebase Authentication

a) In the Firebase Console, go to Authentication > Sign-in method.
b) Enable Google as a sign-in provider.
c) Add your Chrome extension's ID to the authorized domains list:
The format is: chrome-extension://YOUR_EXTENSION_ID
You can find your extension ID in Chrome's extension management page after loading it as an unpacked extension.

Step 5: Load and Test the Extension

a) Open Google Chrome and go to chrome://extensions/.
b) Enable "Developer mode" in the top right corner.
c) Click "Load unpacked" and select your chrome-extension directory.
d) Click on the extension icon in Chrome's toolbar to open the popup.
e) Click the "Sign In" button and test the authentication flow.

Troubleshooting

If you encounter CORS issues, ensure your Firebase hosting URL is correctly set in both background.js and offscreen.js.

Make sure your Chrome extension's ID is correctly added to Firebase's authorized domains.

Check the console logs in the popup, background script, and offscreen document for any error messages.

Conclusion

You now have a Chrome extension that uses Firebase Authentication with an offscreen document to handle the sign-in process. This setup allows for secure authentication without exposing sensitive Firebase configuration details directly in the extension code.

Remember to replace placeholder values (like YOUR_EXTENSION_ID, YOUR-CLIENT-ID, YOUR_PUBLIC_KEY, and your-project-id) with your actual values before publishing your extension.

版本声明 本文转载于:https://dev.to/lvn1/google-authentication-in-a-chrome-extension-with-firebase-2bmo?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何在Java中正确显示“ DD/MM/YYYY HH:MM:SS.SS”格式的当前日期和时间?
    如何在Java中正确显示“ DD/MM/YYYY HH:MM:SS.SS”格式的当前日期和时间?
    如何在“ dd/mm/yyyy hh:mm:mm:ss.ss”格式“ gormat 解决方案: args)抛出异常{ 日历cal = calendar.getInstance(); SimpleDateFormat SDF =新的SimpleDateFormat(“...
    编程 发布于2025-07-03
  • 如何同步迭代并从PHP中的两个等级阵列打印值?
    如何同步迭代并从PHP中的两个等级阵列打印值?
    同步的迭代和打印值来自相同大小的两个数组使用两个数组相等大小的selectbox时,一个包含country代码的数组,另一个包含乡村代码,另一个包含其相应名称的数组,可能会因不当提供了exply for for for the uncore for the forsion for for ytry...
    编程 发布于2025-07-03
  • Java数组中元素位置查找技巧
    Java数组中元素位置查找技巧
    在Java数组中检索元素的位置 利用Java的反射API将数组转换为列表中,允许您使用indexof方法。 (primitives)(链接到Mishax的解决方案) 用于排序阵列的数组此方法此方法返回元素的索引,如果发现了元素的索引,或一个负值,指示应放置元素的插入点。
    编程 发布于2025-07-03
  • Java中假唤醒真的会发生吗?
    Java中假唤醒真的会发生吗?
    在Java中的浪费唤醒:真实性或神话?在Java同步中伪装唤醒的概念已经是讨论的主题。尽管存在这种行为的潜力,但问题仍然存在:它们实际上是在实践中发生的吗? Linux的唤醒机制根据Wikipedia关于伪造唤醒的文章,linux实现了pthread_cond_wait()功能的Linux实现,利用...
    编程 发布于2025-07-03
  • PHP SimpleXML解析带命名空间冒号的XML方法
    PHP SimpleXML解析带命名空间冒号的XML方法
    在php 很少,请使用该限制很大,很少有很高。例如:这种技术可确保可以通过遍历XML树和使用儿童()方法()方法的XML树和切换名称空间来访问名称空间内的元素。
    编程 发布于2025-07-03
  • 您如何在Laravel Blade模板中定义变量?
    您如何在Laravel Blade模板中定义变量?
    在Laravel Blade模板中使用Elegance 在blade模板中如何分配变量对于存储以后使用的数据至关重要。在使用“ {{}}”分配变量的同时,它可能并不总是最优雅的解决方案。幸运的是,Blade通过@php Directive提供了更优雅的方法: $ old_section =“...
    编程 发布于2025-07-03
  • Python中嵌套函数与闭包的区别是什么
    Python中嵌套函数与闭包的区别是什么
    嵌套函数与python 在python中的嵌套函数不被考虑闭合,因为它们不符合以下要求:不访问局部范围scliables to incling scliables在封装范围外执行范围的局部范围。 make_printer(msg): DEF打印机(): 打印(味精) ...
    编程 发布于2025-07-03
  • PHP未来:适应与创新
    PHP未来:适应与创新
    PHP的未来将通过适应新技术趋势和引入创新特性来实现:1)适应云计算、容器化和微服务架构,支持Docker和Kubernetes;2)引入JIT编译器和枚举类型,提升性能和数据处理效率;3)持续优化性能和推广最佳实践。 引言在编程世界中,PHP一直是网页开发的中流砥柱。作为一个从1994年就开始发展...
    编程 发布于2025-07-03
  • 如何限制动态大小的父元素中元素的滚动范围?
    如何限制动态大小的父元素中元素的滚动范围?
    在交互式接口中实现垂直滚动元素的CSS高度限制问题:考虑一个布局,其中我们具有与用户垂直滚动一起移动的可滚动地图div,同时与固定的固定sidebar保持一致。但是,地图的滚动无限期扩展,超过了视口的高度,阻止用户访问页面页脚。$("#map").css({ marginT...
    编程 发布于2025-07-03
  • 如何从Google API中检索最新的jQuery库?
    如何从Google API中检索最新的jQuery库?
    从Google APIS 问题中提供的jQuery URL是版本1.2.6。对于检索最新版本,以前有一种使用特定版本编号的替代方法,它是使用以下语法:获取最新版本:未压缩)While these legacy URLs still remain in use, it is recommended ...
    编程 发布于2025-07-03
  • 为什么HTML无法打印页码及解决方案
    为什么HTML无法打印页码及解决方案
    无法在html页面上打印页码? @page规则在@Media内部和外部都无济于事。 HTML:Customization:@page { margin: 10%; @top-center { font-family: sans-serif; font-weight: bo...
    编程 发布于2025-07-03
  • C++20 Consteval函数中模板参数能否依赖于函数参数?
    C++20 Consteval函数中模板参数能否依赖于函数参数?
    [ consteval函数和模板参数依赖于函数参数在C 17中,模板参数不能依赖一个函数参数,因为编译器仍然需要对非contexexpr futcoriations contim at contexpr function进行评估。 compile time。 C 20引入恒定函数,必须在编译时进行...
    编程 发布于2025-07-03
  • `console.log`显示修改后对象值异常的原因
    `console.log`显示修改后对象值异常的原因
    foo = [{id:1},{id:2},{id:3},{id:4},{id:id:5},],]; console.log('foo1',foo,foo.length); foo.splice(2,1); console.log('foo2', foo, foo....
    编程 发布于2025-07-03
  • 在Python中如何创建动态变量?
    在Python中如何创建动态变量?
    在Python 中,动态创建变量的功能可以是一种强大的工具,尤其是在使用复杂的数据结构或算法时,Dynamic Variable Creation的动态变量创建。 Python提供了几种创造性的方法来实现这一目标。利用dictionaries 一种有效的方法是利用字典。字典允许您动态创建密钥并分...
    编程 发布于2025-07-03

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3