Google의 공식 가이드에는 몇 가지 중요한 단계가 누락되어 있어 이 가이드를 작성하고 있습니다. 아래 링크를 참조하세요.
Chrome 확장 프로그램에서 Firebase로 인증
이 방법은 모든 운영 체제에서 작동합니다. 이 가이드에서는 Mac OS를 사용합니다
전제 조건
- Google 크롬 브라우저
- 구글 계정
- Chrome 웹 스토어 개발자 계정(1회 수수료 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) 생성이 완료되면 "웹"을 클릭하여 프로젝트에 웹 앱을 추가하세요.
d) 닉네임(예: "Chrome Extension Auth")으로 앱을 등록하세요.
e) Firebase 구성 객체를 복사합니다. 나중에 필요합니다.
const firebaseConfig = { apiKey: "example", authDomain: "example.firebaseapp.com", projectId: "example", storageBucket: "example", messagingSenderId: "example", appId: "example" };
f) firebase-project 디렉토리로 이동
CD Firebase 프로젝트
g) 새 npm 프로젝트 초기화
npm 초기화 -y
h) Firebase 설치:
npm Firebase 설치
i) firebase-project/index.html
에 index.html 파일을 생성합니다.
<title>Firebase Auth for Chrome Extension</title> <h1 id="Firebase-Auth-for-Chrome-Extension">Firebase Auth for Chrome Extension</h1> <script type="module" src="signInWithPopup.js"></script>
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 ../크롬 확장
b) chrome-extension/manifest.json
에 매니페스트.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-----" } </all_urls>
c) chrome-extension/popup.html
에 popup.html 파일을 만듭니다.
<title>Firebase Auth Extension</title> <h1 id="Firebase-Auth-Extension">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>
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 파일을 만듭니다.
<title>Offscreen Document</title> <script src="offscreen.js"></script>
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-extension 디렉토리를 선택하세요.
d) Chrome 툴바에서 확장 프로그램 아이콘을 클릭하여 팝업을 엽니다.
e) "로그인" 버튼을 클릭하고 인증 흐름을 테스트하세요.
문제 해결
CORS 문제가 발생하면 background.js와 offscreen.js 모두에서 Firebase 호스팅 URL이 올바르게 설정되었는지 확인하세요.
Chrome 확장 프로그램의 ID가 Firebase의 승인된 도메인에 올바르게 추가되었는지 확인하세요.
팝업, 백그라운드 스크립트, 오프스크린 문서의 콘솔 로그에서 오류 메시지를 확인하세요.
결론
이제 오프스크린 문서와 함께 Firebase 인증을 사용하여 로그인 프로세스를 처리하는 Chrome 확장 프로그램이 생겼습니다. 이 설정을 사용하면 민감한 Firebase 구성 세부정보를 확장 코드에 직접 노출하지 않고도 보안 인증이 가능합니다.
확장 프로그램을 게시하기 전에 자리 표시자 값(예: YOUR_EXTENSION_ID, YOUR-CLIENT-ID, YOUR_PUBLIC_KEY 및 your-project-id)을 실제 값으로 바꾸는 것을 잊지 마세요.
위 내용은 Firebase를 사용한 Chrome 확장 프로그램의 Google 인증의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

JavaScript 문자열 교체 방법 및 FAQ에 대한 자세한 설명 이 기사는 JavaScript에서 문자열 문자를 대체하는 두 가지 방법 인 내부 JavaScript 코드와 웹 페이지의 내부 HTML을 탐색합니다. JavaScript 코드 내부의 문자열을 교체하십시오 가장 직접적인 방법은 대체 () 메소드를 사용하는 것입니다. str = str.replace ( "find", "replace"); 이 메소드는 첫 번째 일치 만 대체합니다. 모든 경기를 교체하려면 정규 표현식을 사용하고 전역 플래그 g를 추가하십시오. str = str.replace (/fi

이 튜토리얼은 사용자 정의 Google 검색 API를 블로그 또는 웹 사이트에 통합하는 방법을 보여 주며 표준 WordPress 테마 검색 기능보다보다 세련된 검색 경험을 제공합니다. 놀랍게도 쉽습니다! 검색을 Y로 제한 할 수 있습니다

이 기사 시리즈는 2017 년 중반에 최신 정보와 새로운 예제로 다시 작성되었습니다. 이 JSON 예에서는 JSON 형식을 사용하여 파일에 간단한 값을 저장하는 방법을 살펴 봅니다. 키 값 쌍 표기법을 사용하여 모든 종류를 저장할 수 있습니다.

코드 프레젠테이션 향상 : 개발자를위한 10 개의 구문 하이 라이터 웹 사이트 나 블로그에서 코드 스 니펫을 공유하는 것은 개발자에게 일반적인 관행입니다. 올바른 구문 형광펜을 선택하면 가독성과 시각적 매력을 크게 향상시킬 수 있습니다. 티

그래서 여기 당신은 Ajax라는이 일에 대해 배울 준비가되어 있습니다. 그러나 정확히 무엇입니까? Ajax라는 용어는 역동적이고 대화식 웹 컨텐츠를 만드는 데 사용되는 느슨한 기술 그룹을 나타냅니다. 원래 Jesse J에 의해 만들어진 Ajax라는 용어

손쉬운 웹 페이지 레이아웃에 대한 jQuery 활용 : 8 에센셜 플러그인 jQuery는 웹 페이지 레이아웃을 크게 단순화합니다. 이 기사는 프로세스를 간소화하는 8 개의 강력한 JQuery 플러그인을 강조합니다. 특히 수동 웹 사이트 생성에 유용합니다.

이 기사는 JavaScript 및 JQuery Model-View-Controller (MVC) 프레임 워크에 대한 10 개가 넘는 튜토리얼을 선별 한 것으로 새해에 웹 개발 기술을 향상시키는 데 적합합니다. 이 튜토리얼은 Foundatio의 다양한 주제를 다룹니다

핵심 포인트 JavaScript에서는 일반적으로 메소드를 "소유"하는 객체를 말하지만 함수가 호출되는 방식에 따라 다릅니다. 현재 객체가 없으면 글로벌 객체를 나타냅니다. 웹 브라우저에서는 창으로 표시됩니다. 함수를 호출 할 때 이것은 전역 객체를 유지하지만 객체 생성자 또는 그 메소드를 호출 할 때는 객체의 인스턴스를 나타냅니다. call (), apply () 및 bind ()와 같은 메소드를 사용 하여이 컨텍스트를 변경할 수 있습니다. 이 방법은 주어진이 값과 매개 변수를 사용하여 함수를 호출합니다. JavaScript는 훌륭한 프로그래밍 언어입니다. 몇 년 전,이 문장은있었습니다


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

드림위버 CS6
시각적 웹 개발 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.
