Hike News
Hike News

ChatGPT로 chrome 확장만들기

Person:

1
2
3
4
5
6
1. 크롬익스텐션을 만듭니다.
2. popup.html내에 버튼이 있습니다.
3. 버튼을 클릭하면 popup.html을 호출했던 브라우저에서
하이라이트로 선택된 문자열을 가지고 옵니다.
4. 버튼 아래에 문자열을 출력합니다.
5. version 3 코드로 만들어주세요

ChatGPT:

크롬 확장 프로그램을 개발하기 위해서는 다음과 같은 파일과 코드가 필요합니다:

  1. manifest.json 파일: 크롬 확장 프로그램의 설정 정보를 담고 있는 파일입니다.
  2. popup.html 파일: 팝업 창의 내용을 담고 있는 HTML 파일입니다.
  3. popup.js 파일: 팝업 창의 동작을 제어하는 JavaScript 코드입니다.

아래는 요구사항을 충족하는 크롬 확장 프로그램의 코드입니다. 이 코드는 JavaScript의 최신 문법인 ES6 문법을 사용하고, 버튼 클릭 시 하이라이트로 선택된 문자열을 가져와 팝업 창에 출력합니다.

  1. manifest.json 파일:
1
2
3
4
5
6
7
8
9
10
11
12

{
"manifest_version": 3,
"name": "My Chrome Extension",
"version": "1.0",
"action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
]
}
  1. popup.html 파일:
1
2
3
4
5
6
7
8
9
10
11
12

<!DOCTYPE html>
<html>
<head>
<title>My Chrome Extension</title>
<script src="popup.js"></script>
</head>
<body>
<button id="highlightButton">하이라이트된 문자열 가져오기</button>
<div id="highlightedText"></div>
</body>
</html>
  1. popup.js 파일:
1
2
3
4
5
6
7
8
9
10
11
12
13

document.addEventListener("DOMContentLoaded", function() {
// 버튼 클릭 이벤트 핸들러 등록
document.getElementById("highlightButton").addEventListener("click", function() {
// 현재 탭의 내용을 가져오기 위한 실행 스크립트 주입
chrome.tabs.executeScript({
code: "window.getSelection().toString();"
}, function(result) {
// 가져온 문자열을 팝업 창에 출력
document.getElementById("highlightedText").textContent = result[0];
});
});
});

위의 코드를 복사하여 각각 manifest.json, popup.html, popup.js 파일로 저장한 뒤, 크롬 브라우저의 확장 프로그램 관리 페이지(chrome://extensions/)에서 “개발자 모드”를 활성화하고 “압축해제된 확장 프로그램을 로드합니다” 버튼을 클릭하여 해당 디렉토리를 선택하면 확장 프로그램이 설치됩니다.

이제 크롬 브라우저에서 확장 프로그램 아이콘을 클릭하면 팝업 창이 열리고, 버튼을 클릭하면 현재 탭에서 하이라이트로 선택된 문자열이 팝업 창에 출력됩니다.

Person:

1
2
3
4
1.  popup.html에서 한글이 깨지지 말게 해주세요
2. popup의 크기는 가로 400, 세로 400으로 해주세요
3. 배경을 노란색으로 해주세요
소스를 고쳐주세요

ChatGPT:

요구사항에 맞게 수정된 코드는 다음과 같습니다:

  1. popup.html 파일:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

<!DOCTYPE html>
<html>
<head>
<title>My Chrome Extension</title>
<meta charset="UTF-8">
<style>
body {
width: 400px;
height: 400px;
background-color: yellow;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<button id="highlightButton">하이라이트된 문자열 가져오기</button>
<div id="highlightedText"></div>
</body>
</html>

주요 변경사항:

  • <meta charset="UTF-8">을 추가하여 한글 문자열이 깨지지 않도록 설정합니다.
  • <style> 태그를 사용하여 body 요소의 크기를 400px로 설정하고 배경색을 노란색으로 지정합니다.

이제 한글 문자열은 깨지지 않고, 팝업 창의 크기가 400x400이며 배경색이 노란색으로 지정됩니다.

Person:

  • Uncaught TypeError: chrome.tabs.executeScript is not a function 메시지가 나타납니다.

ChatGPT:

  • chrome.tabs.executeScript 함수를 사용하려면 manifest.json 파일에서 해당 권한을 명시해야 합니다. 다음과 같이 manifest.json 파일을 수정하여 tabs 권한을 추가해주세요:
1
2
3
4
5
6
7
8
9
10
11
12
13

{
"manifest_version": 3,
"name": "My Chrome Extension",
"version": "1.0",
"action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"tabs"
]
}

manifest.json 파일에서 "permissions" 배열에 "tabs"를 추가하여 권한을 설정하였습니다. 이제 다시 실행하면 chrome.tabs.executeScript 함수가 정상적으로 동작할 것입니다.

Person:

1
2
3
4
5
6
7
chrome.tabs.executeScript({
code: "window.getSelection().toString();"
}, function(result) {
// 가져온 문자열을 팝업 창에 출력
document.getElementById("highlightedText").textContent = result[0];
});
에서 Uncaught TypeError: chrome.tabs.executeScript is not a function에러가 납니다.

ChatGPT:

  • chrome.tabs.executeScript 함수가 사용되는 부분에서 발생하는 Uncaught TypeError: chrome.tabs.executeScript is not a function 오류는 보통 chrome.tabs API에 접근할 수 없어서 발생합니다.

이 오류가 발생하는 이유는 manifest.json 파일의 "manifest_version"이 3으로 설정되어 있기 때문입니다. GPT-3.5 기준으로는 최신인 manifest_version 3은 일부 API와 호환되지 않을 수 있습니다.

이 문제를 해결하기 위해서는 manifest.json 파일의 "manifest_version"을 2로 변경하고, "background" 속성을 추가하여 백그라운드 스크립트를 사용하여 작업을 수행해야 합니다. 아래는 수정된 코드입니다:

  1. manifest.json 파일:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

{
"manifest_version": 2,
"name": "My Chrome Extension",
"version": "1.0",
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
  1. popup.js 파일:
1
2
3
4
5
6
7
8

document.addEventListener("DOMContentLoaded", function() {
// background 스크립트에 메시지 전송
chrome.runtime.sendMessage({ action: "getHighlightedText" }, function(response) {
// 가져온 문자열을 팝업 창에 출력
document.getElementById("highlightedText").textContent = response.highlightedText;
});
});
  1. background.js 파일:
1
2
3
4
5
6
7
8
9
10
11
12

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === "getHighlightedText") {
// 현재 탭의 내용을 가져오기 위한 실행 스크립트 주입
chrome.tabs.executeScript({
code: "window.getSelection().toString();"
}, function(result) {
sendResponse({ highlightedText: result[0] });
});
return true; // 비동기 응답을 위해 true 반환
}
});

위의 코드를 적용하면 "manifest_version"이 2로 변경되었고, background.js 파일이 추가되어 백그라운드 스크립트로 동작합니다. 이를 통해 chrome.tabs API에 접근하여 문제를 해결할 수 있습니다.

Person:

  • “manifest_version”: 2는 지원하지 않습니다. 다른 방법으로 찾아주세요

ChatGPT:

  • 죄송합니다. manifest_version 2를 사용할 수 없다는 정보를 드려 대단히 죄송합니다. manifest_version 3를 사용하며 동작하는 다른 방법을 찾아보도록 하겠습니다.

다음은 manifest_version 3를 사용하며 chrome.scripting API를 활용하는 방법입니다. 이 방법으로도 하이라이트된 문자열을 가져올 수 있습니다.

  1. manifest.json 파일:
1
2
3
4
5
6
7
8
9
10
11
12
13

{
"manifest_version": 3,
"name": "My Chrome Extension",
"version": "1.0",
"action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"scripting"
]
}
  1. popup.js 파일:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

document.addEventListener("DOMContentLoaded", function() {
// 버튼 클릭 이벤트 핸들러 등록
document.getElementById("highlightButton").addEventListener("click", async function() {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const result = await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: getSelectedText
});
document.getElementById("highlightedText").textContent = result[0].result;
} catch (error) {
console.error(error);
}
});
});

// 현재 탭에서 선택된 텍스트를 반환하는 함수
function getSelectedText() {
return window.getSelection().toString();
}

위의 코드는 chrome.scripting.executeScript 함수를 사용하여 선택된 텍스트를 가져오는 방식으로 수정되었습니다. 또한, async/await 문법을 사용하여 비동기 작업을 처리하고 있습니다.

이제 위의 코드를 사용하여 크롬 확장 프로그램을 다시 실행해보세요. 버튼을 클릭하면 선택된 텍스트가 팝업 창에 출력됩니다. 이 방법은 manifest_version 3와 chrome.scripting API를 사용하여 문제를 해결합니다.

Person:

  • popup.html에서 버튼을 삭제해주고 popup.html이 뜰때
    버튼이 눌렀을 때의 효과를 만들어주세요

ChatGPT:

  • popup.html에서 버튼을 삭제하고, 팝업 창이 열렸을 때 효과를 만들기 위해 다음과 같이 코드를 수정할 수 있습니다:
  1. popup.html 파일:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

<!DOCTYPE html>
<html>
<head>
<title>My Chrome Extension</title>
<meta charset="UTF-8">
<style>
body {
width: 400px;
height: 400px;
background-color: yellow;
}
#highlightedText {
margin-top: 20px;
font-size: 18px;
text-align: center;
}
</style>
<script src="popup.js"></script>
</head>
<body>
<div id="highlightedText"></div>
</body>
</html>

주요 변경사항:

  • 버튼 요소를 삭제하고, 스타일을 조정하여 효과를 만들 준비를 합니다.
  • highlightedText 요소에 상단 여백과 폰트 크기, 텍스트 정렬 스타일을 적용합니다.
  1. popup.js 파일:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

document.addEventListener("DOMContentLoaded", async function() {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const result = await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: getSelectedText
});
document.getElementById("highlightedText").textContent = result[0].result;
} catch (error) {
console.error(error);
}
});

// 현재 탭에서 선택된 텍스트를 반환하는 함수
function getSelectedText() {
return window.getSelection().toString();
}

주요 변경사항:

  • DOMContentLoaded 이벤트 핸들러 내부에서 바로 선택된 텍스트를 가져오도록 코드를 수정합니다.
  • highlightedText 요소에 선택된 텍스트를 설정합니다.

위의 코드를 적용하면 팝업 창이 열리면 자동으로 선택된 텍스트를 가져와서 highlightedText 요소에 출력됩니다. 버튼 없이 팝업 창이 열릴 때마다 효과가 나타납니다.

Person:

1
2
3
4
1. 버튼을 삭제
2. 문자열을 출력할 highlightedText의 padding을 30으로 설정
3. highlightedText 뒤에 div를 만들고 배경을 검은색 반투명으로 30% 설정
해주세요

ChatGPT:

  • 수정된 popup.html 코드는 다음과 같습니다:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

<!DOCTYPE html>
<html>
<head>
<title>My Chrome Extension</title>
<meta charset="UTF-8">
<style>
body {
width: 400px;
height: 400px;
background-color: yellow;
}
#highlightedText {
padding: 30px;
font-size: 18px;
text-align: center;
}
#overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
}
</style>
<script src="popup.js"></script>
</head>
<body>
<div id="highlightedText"></div>
<div id="overlay"></div>
</body>
</html>

주요 변경사항:

  • padding 값을 30으로 설정하여 highlightedText 요소의 내부 여백을 조정합니다.
  • overlay라는 새로운 div 요소를 추가하고, 검은색 배경에 30%의 투명도를 가지도록 스타일을 지정합니다.

이제 팝업 창이 열리면 버튼 없이 문자열이 출력되고, highlightedText 요소의 패딩이 30으로 설정되며, overlay 요소가 검은색으로 반투명하게 나타납니다.

Person:

  • popup.html에 구글폰트를 적용해주세요

ChatGPT:

  • 구글 폰트를 popup.html에 적용하려면 다음과 같이 코드를 수정할 수 있습니다:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

<!DOCTYPE html>
<html>
<head>
<title>My Chrome Extension</title>
<meta charset="UTF-8">
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');

body {
width: 400px;
height: 400px;
background-color: yellow;
font-family: 'Roboto', sans-serif;
}

#highlightedText {
padding: 30px;
font-size: 18px;
text-align: center;
}

#overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.3);
}
</style>
<script src="popup.js"></script>
</head>
<body>
<div id="highlightedText"></div>
<div id="overlay"></div>
</body>
</html>

주요 변경사항:

  • @import 문을 사용하여 구글 폰트 ‘Roboto’를 가져옵니다.
  • body 스타일에서 font-family 속성을 'Roboto', sans-serif로 설정하여 폰트를 적용합니다.

이제 팝업 창이 열릴 때 구글 폰트 ‘Roboto’가 적용되어 문자열이 표시됩니다.