Popup.html 파일은  Todo 내용을 저장 있도록 간단하게 구성하였다.

( CSS 파일을 사용하지 않았지만, 화면에 맞게 CSS 구성하여 import 하여 사용도 가능하다. )

 

  • popup.html

<!DOCTYPE html>

<head>

<meta charset="UTF-8">

<script src="jquery-3.3.1.min.js"></script>

<script src='popup.js'></script>

</head>

<body>

<input id="todo">

<button id="save">저장</button>

</body>

 

코드에서는 selector 편의성을 위해서 jQuery 추가하였다.

 

, jQuery 사용하려고 할때, CDN 이용해서 사용할 수가 없다.

따라서 jQuery 파일을 다운 받고, 크롬 확장프로그램 폴더에 추가한 다음에 사용하면 된다.

 

실제 화면에서 사용되는 사용되는 스크립트 파일은 popup.js 되며, 소스는 내용은 아래와 같다.

 

  • popup.js

$(document).ready(function(){

$('#save').on('click',function(){

if ( $('#todo').val() ){

chrome.storage.sync.get(null, function(items) {

var allKeys = Object.keys(items);

if ( allKeys.length >= 3){

alert('더이상 저장 할 수 없습니다.');

return;

}

let message = $('#todo').val();

let timeStamp = getTimeStamp();

chrome.storage.sync.set({[timeStamp] : message}, function() {

$('#todo').val('');

chrome.runtime.sendMessage({'notificationId' : timeStamp}, function(){});

});

});

}else{

alert('내용을 입력해주세요.');

}

});

});

/**

* 현재 시간 정보 가져오기

*/

function getTimeStamp(){

let d = new Date();

let result = '';

result += zeroPadding(d.getHours()) + ':';

result += zeroPadding(d.getMinutes()) + ':';

result += zeroPadding(d.getSeconds());

return result;

}

/**

* 10의 자릿수로 설정

* @param {*} num 숫자

*/

function zeroPadding(num){

if ( num < 10 ){

return '0' + num;

}

return num;

}

 

Chrome storage 입력한 시간을 Key, 입력한 값을 value 사용하여 데이터를 저장하고,

 

sendMessage 통하여 데이터를 background.js 전송하도록 하였다.

 

모든 처리를 popup.js 하지 않고, background.js 데이터를 전송하는 이유는

 

Popup.js에서 사용할 있는 chrome.API 제한이 있다. 따라서 본인이 사용하고자 하는 API content영역에서 사용할 있는지 확인 필요하다.

 

(설정에서 추가한 notification api content영역에서 사용할 없어서 데이터를 background.js 전송 , notification 사용하였다.)


Notification의 경우, content에서도 사용 가능하다. tutorial에서는 content.js와 background.js간의 통신부분만 이해하면 된다.


'프로그래밍 > Chrome Extension' 카테고리의 다른 글

크롬 확장프로그램 tutorial 1  (0) 2019.03.23