Background.js 파일은 백그라운드에서 동작하는 기능을 설정할 있다.

 

현재는 TODO 정보를 백그라운드에서 알림창을 사용하여 화면에 표현해주는 내용을 작성한 것이다.

 

  • background.js

chrome.runtime.onMessage.addListener(message =>{

createNotification(message['notificationId']);

return true;

});

/**

* 알림창 옵션 생성

*/

function getNotificationOption(notificationId){

return new Promise(function(resolve, reject){

try{

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

let notificationsOption = {

type: "basic",

title: "TODO Notification!",

iconUrl : 'icon.png',

message: items[notificationId],

requireInteraction : true

}

resolve(notificationsOption);

});

}catch(e){

reject();

}

});

}

/**

* 알림 생성

*/

function createNotification( notificationId ){

getNotificationOption(notificationId).then(function(value) {

chrome.notifications.create(notificationId, value, function(){

});

});

}

/**

* 알림 업데이트

*/

function clickedNotification( notificationId ){

if ( confirm('완료했나요?') ){

chrome.storage.sync.remove(notificationId, function(){});

}else{

getNotificationOption(notificationId).then(function(value) {

chrome.notifications.update(notificationId, value, function(){});

});

return;

}

}

 

chrome.notifications.onClicked.addListener(clickedNotification);

 

 

백그라운드에서는 리스너를 사용하여 popup.js에서 전송되는 메시지 정보를 전달 받을 있도록 해둔다.

 

전달받은 메시지 내용을 기반으로 알림창을 생성하게 된다.

 

알림창 옵션에서 iconUrl 필수 옵션이므로, 알림창 icon영역에 표현될 이미지 파일을 추가해야 한다.

 

이미지 파일은 크롬 확장프로그램 폴더에 동일하게 위치 시키면 된다.

 

알림창 옵션 , requireInteraction true 지정하지 않으면, 알림창은 수초 이내로 자동으로 사라지게 되어있다.

 

따라서 알림창을 클릭하기 전까지 항상 유지하도록 설정하였다.

 

알림창을 클릭하면 알림창을 닫을지 여부를 확인하여, 나머지 작업을 처리하도록 하였다.

 

지금까지 간단하게 입력창을 통하여 데이터를 저장하고, 알림창까지 띄우는 내용을 진행했다.

(다만, 메시지를 전달 받은 , 비동기 동작(storage에서 데이터를 꺼내는 작업)으로 인하여, 콘솔창에 오류가 발생한다. )

 

크롬 확장프로그램은 기본적으로 스크립트와 html 이뤄져있기 때문에, 크롬 확장프로그램 규격에 맞는 구성과 API 사용하면,

 

본인이 원하는 내용은 간단하게 만들어서 사용이 가능하다. ( : 달력연동, 모니터링 기능 등등 )




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



크롬 확장프로그램 개발은 js, html, 그리고 Manifest File 구성되어 개발이 된다.

 

크롬 확장 프로그램에 필요한 js, html 그리고 Manifest file 하나의 폴더에 두고,

 

크롬을 실행하여 주소입력창에 chrome://extensions 입력하면, 확장프로그램 페이지로 이동한다.

 

개발자 모드(Developer mode) 켜주면, 숨겨진 바가 나온다. 


거기서 "압축해제된 확장 프로그램을 로드합니다.(Load unpacked)" 클릭하면,

 

폴더를 선택할 있는 창이 나온다


여기서 크롬 확장프로그램에 필요한 파일들이 들어있는 폴더를 선택하면 된다.

 

그러면 크롬에 확장 프로그램이 추가된다.

 

크롬 확장 프로그램에서 manifest.json 파일 설정에 따라 필요한 js,html 있으므로


간단하게 작성해 보면 아래와 같다.

 

{

"name": "Tutorial",

"version": "1.0",

"description": "run to Simple",

"permissions":      ["storage","notifications"],

"background": {

"scripts": ["background.js"],

"persistent": false

},

"browser_action": {

"default_popup":"popup.html"

},

"manifest_version": 2

}

 

manifest.json에서 필수로 선언되어야 하는 내용은 name, version, manifest_version 3가지 이고,


manifest_version 2 설정해야된다.

 

상세 내용은 공식 홈페이지 참조 (https://developer.chrome.com/extensions/manifest)

 

위와 같이 설정을 하게 되면 필요한 파일은

 

- Background.js

- popup.html

- popup.js ( popup.html 내에서 사용될 자바스크립 )

 

추가적으로 ajax selector 사용하기 위하여 옵션적으로 jQuery.js 파일을 추가해서 사용해도 된다.





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

크롬 확장프로그램 tutorial 2  (0) 2019.03.24