Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEAT] 현재 탭에서 데이터 가져오기 #50

Merged
merged 13 commits into from
Sep 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions frontend/.pnp.cjs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion frontend/techpick-extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"typescript": "^5.5.3",
"typescript-eslint": "^8.0.1",
"vite": "^5.4.1",
"vite-plugin-static-copy": "^1.0.6"
"vite-plugin-static-copy": "^1.0.6",
"vite-tsconfig-paths": "^5.0.1"
}
}
13 changes: 0 additions & 13 deletions frontend/techpick-extension/src/chorme-extension/manifest.json

This file was deleted.

Empty file.
20 changes: 20 additions & 0 deletions frontend/techpick-extension/src/chrome-extension/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"manifest_version": 3,
"name": "TechPick Extension",
"description": "TechPick Extension description",
"version": "0.1",
"permissions": ["tabs", "activeTab", "scripting"],
"background": {
"service_worker": "background.js",
"type": "module"
},
"content_scripts": [
{
"matches": ["https://*/*", "http://*/*"],
"js": ["contentscript.js"]
}
],
"action": {
"default_popup": "index.html"
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { style } from '@vanilla-extract/css';

export const container = style({ width: '300px', backgroundColor: 'red' });
export const container = style({ width: '300px', backgroundColor: 'white' });
45 changes: 17 additions & 28 deletions frontend/techpick-extension/src/components/CurrentTabInfo.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,22 @@
import React, { useEffect, useState } from 'react';
import { container } from './CurrentTabInfo.css';
import { useGetTabInfo } from '@/hooks';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tab 정보를 가져오는 부분을 hook으로 분리해서 코드가 더 깔끔해졌네요!


export const CurrentTabInfo: React.FC = () => {
const [tabInfo, setTabInfo] = useState<{ title: string; url: string } | null>(
null
);

useEffect(() => {
const getCurrentTab = async () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs[0]) {
setTabInfo({
title: tabs[0].title || 'No Title',
url: tabs[0].url || 'No URL',
});
}
});
};

getCurrentTab();
}, []);

if (!tabInfo) return <div>Loading...</div>;
export function CurrentTabInfo() {
const tabInfo = useGetTabInfo();

return (
<div className={container}>
<h1>Current Tab Info</h1>
<p>Title: {tabInfo.title}</p>
<p>URL: {tabInfo.url}</p>
<div>
<h2>{tabInfo?.title}</h2>
<p>URL: {tabInfo?.url}</p>
{tabInfo?.favicon ? (
<img src={tabInfo?.favicon} alt="Favicon" />
) : (
<p>No Favicon</p>
)}
{tabInfo.ogDescription ? (
<p>{tabInfo.ogDescription}</p>
) : (
<p>No Og description</p>
)}
</div>
);
};
}
Empty file.
1 change: 1 addition & 0 deletions frontend/techpick-extension/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useGetTabInfo } from './useGetTabInfo/useGetTabInfo';
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// executeScript는 전달된 함수의 실행 컨텍스트가 전역 스코프가 되기 때문에, 외부에서 정의한 함수에 접근할 수 없습니다.
const getPageInfoFromDom = () => {
const getFaviconFromDom = () => {
const faviconLink =
document.querySelector("link[rel='icon']") ||
document.querySelector("link[rel='shortcut icon']") ||
document.querySelector('link');

return faviconLink instanceof HTMLLinkElement ? faviconLink.href : null;
};

const getOgDescriptionFromDom = () => {
const ogDescriptionMeta = document.querySelector(
"meta[property='og:description']"
);

return ogDescriptionMeta instanceof HTMLMetaElement
? ogDescriptionMeta.content
: null;
};

const faviconUrl = getFaviconFromDom();
const ogDescription = getOgDescriptionFromDom();

return {
faviconUrl,
ogDescription,
};
};

export const fetchFaviconAndDescription = async (tabId: number) => {
const results = await chrome.scripting.executeScript({
target: { tabId },
func: getPageInfoFromDom,
});

return results[0].result;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { useEffect, useState } from 'react';
import { fetchFaviconAndDescription } from './useGetTabInfo.lib';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useGetTabInfo.lib의 간단한 설명을 요청드리고 싶습니다!
해당 부분이 chrome extension이 웹 페이지에서 필요한 정보를 가져오는 api의 구현체인가요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

export const fetchFaviconAndDescription = async (tabId: number) => {
  const results = await chrome.scripting.executeScript({
    target: { tabId },
    func: getPageInfoFromDom,
  });

  return results[0].result;
};

이 부분은 그렇게 보셔도 될 것 같습니다! 공신 문서의 링크를 첨부할게요!
참고 링크


interface TabInfo {
title: string | undefined;
url: string | undefined;
favicon?: string | undefined | null;
ogDescription?: string | undefined | null;
}

export function useGetTabInfo() {
const [tabInfo, setTabInfo] = useState<TabInfo>({
title: undefined,
url: undefined,
});

useEffect(() => {
const getTabInfo = async () => {
// 현재 탭 정보 가져오기
const tabs = await chrome.tabs.query({
active: true,
currentWindow: true,
});
const tab = tabs[0];
setTabInfo({
title: tab.title,
url: tab.url,
});

// http가 아닌 다른 URL(ex: chrome)은 권한이 없어서 확장 프로그램에서 에러가 날 수 있습니다.
if (tab.url && !tab.url.startsWith('http')) {
return;
}

if (!tab.id) {
return;
}

const result = await fetchFaviconAndDescription(tab.id);

if (!result) {
return;
}

setTabInfo((prev) => ({
...prev,
favicon: result?.faviconUrl,
ogDescription: result?.ogDescription,
}));
};

getTabInfo();
}, []);

return tabInfo;
}
10 changes: 10 additions & 0 deletions frontend/techpick-extension/src/pages/BookmarkPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { CurrentTabInfo } from '@/components';

export function BookmarkPage() {
return (
<>
<h1>Bookmark page</h1>
<CurrentTabInfo />
</>
);
}
1 change: 1 addition & 0 deletions frontend/techpick-extension/src/pages/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { BookmarkPage } from './BookmarkPage';
9 changes: 2 additions & 7 deletions frontend/techpick-extension/src/routers/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import { createMemoryRouter } from 'react-router-dom';
import { CurrentTabInfo } from '../components';
import { BookmarkPage } from '../pages';

export const router = createMemoryRouter([
{
path: '/',
element: (
<>
<h1>Main Page</h1>
<CurrentTabInfo />
</>
),
element: <BookmarkPage />,
},
{
path: '/login',
Expand Down
1 change: 1 addition & 0 deletions frontend/techpick-extension/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './message';
16 changes: 16 additions & 0 deletions frontend/techpick-extension/src/types/message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export type RequestMessageType = string;

export type ResponseMessageType = {
type: string;
};

export type ResponseOgImageType = {
type: 'OG_IMAGE' | string;
ogImageUrl: string | null;
};

export const isResponseOgImageType = (
message: ResponseMessageType
): message is ResponseOgImageType => {
return message.type === 'OG_IMAGE' && 'ogImageUrl' in message;
};
4 changes: 4 additions & 0 deletions frontend/techpick-extension/tsconfig.app.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
Expand Down
2 changes: 1 addition & 1 deletion frontend/techpick-extension/tsconfig.app.tsbuildinfo
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"root":["./src/App.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/chorme-extension/background.ts","./src/components/CurrentTabInfo.css.ts","./src/components/CurrentTabInfo.tsx","./src/components/index.ts","./src/features/index.ts","./src/hooks/index.ts","./src/lib/index.ts","./src/pages/index.ts","./src/routers/index.tsx","./src/widgets/index.ts"],"version":"5.6.2"}
{"root":["./src/App.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/chrome-extension/background.ts","./src/chrome-extension/contentscript.ts","./src/components/CurrentTabInfo.css.ts","./src/components/CurrentTabInfo.tsx","./src/components/index.ts","./src/constants/index.ts","./src/constants/message.ts","./src/features/index.ts","./src/hooks/index.ts","./src/hooks/useGetTabInfo/useGetTabInfo.lib.ts","./src/hooks/useGetTabInfo/useGetTabInfo.tsx","./src/lib/index.ts","./src/pages/BookmarkPage.tsx","./src/pages/index.ts","./src/routers/index.tsx","./src/types/index.ts","./src/types/message.ts","./src/widgets/index.ts"],"version":"5.6.2"}
4 changes: 4 additions & 0 deletions frontend/techpick-extension/tsconfig.node.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
Expand Down
14 changes: 8 additions & 6 deletions frontend/techpick-extension/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@ import react from '@vitejs/plugin-react';
import { resolve } from 'path';
import { viteStaticCopy } from 'vite-plugin-static-copy';
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';
import tsconfigPaths from 'vite-tsconfig-paths';

// https://vitejs.dev/config/
export default defineConfig({
build: {
watch: {
include: 'src/**',
exclude: 'node_modules/**',
},
rollupOptions: {
input: {
background: resolve(__dirname, 'src/chorme-extension/background.ts'),
background: resolve(__dirname, 'src/chrome-extension/background.ts'),
popup: resolve(__dirname, './index.html'),
contentscript: resolve(
__dirname,
'./src/chrome-extension/contentscript.ts'
),
},
output: {
entryFileNames: '[name].js',
Expand All @@ -25,8 +26,9 @@ export default defineConfig({
plugins: [
react(),
viteStaticCopy({
targets: [{ src: './src/chorme-extension/manifest.json', dest: '.' }],
targets: [{ src: './src/chrome-extension/manifest.json', dest: '.' }],
}),
vanillaExtractPlugin(),
tsconfigPaths(),
],
});
Loading