Event Page Example

2015. 5. 2. 16:55 - mr.november11

[크롬 익스텐션 개발하기]

Chrome Extension Sample page 소스분석

https://developer.chrome.com/extensions/samples


manifest.json

해당 프로그램의 permission을 알람, 탭, 북마크, web requset 로 선언

Ctrl+Shift+K가 눌렸을 시 browser action을 실행하도록 설정한다.

MAX OS의 경우 Ctrl 대신 Command 버튼을 선택하면 된다.

{
  "name": "Event Page Example",
  "description": "Demonstrates usage and features of the event page",
  "version": "1.0",
  "manifest_version": 2,
  "permissions": ["alarms", "tabs", "bookmarks", "declarativeWebRequest", "*://*/*"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon" : "icon.png",
    "default_title": "Start Event Page"
  },
  "commands": {
    "open-google": {
      "description": "Open a tab to google.com",
      "suggested_key": { "default": "Ctrl+Shift+L" }
    },
    "_execute_browser_action": {
      "suggested_key": { "default": "Ctrl+Shift+K" }
    }
  }
}

background.js


// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Global variables only exist for the life of the page, so they get reset
// each time the page is unloaded.
var counter = 1;

var lastTabId = -1;
function sendMessage() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    lastTabId = tabs[0].id;
    chrome.tabs.sendMessage(lastTabId, "Background page started.");
  });
}

sendMessage();
chrome.browserAction.setBadgeText({text: "ON"});
console.log("Loaded.");

chrome.runtime.onInstalled.addListener(function() {
  console.log("Installed.");

  // localStorage is persisted, so it's a good place to keep state that you
  // need to persist across page reloads.
  localStorage.counter = 1;

  // Register a webRequest rule to redirect bing to google.
  var wr = chrome.declarativeWebRequest;
  chrome.declarativeWebRequest.onRequest.addRules([{
    id: "0",
    conditions: [new wr.RequestMatcher({url: {hostSuffix: "bing.com"}})],
    actions: [new wr.RedirectRequest({redirectUrl: "http://google.com"})]
  }]);
});

chrome.bookmarks.onRemoved.addListener(function(id, info) {
  alert("I never liked that site anyway.");
});

chrome.browserAction.onClicked.addListener(function() {
  // The event page will unload after handling this event (assuming nothing
  // else is keeping it awake). The content script will become the main way to
  // interact with us.
  chrome.tabs.create({url: "http://google.com"}, function(tab) {
    chrome.tabs.executeScript(tab.id, {file: "content.js"}, function() {
      // Note: we also sent a message above, upon loading the event page,
      // but the content script will not be loaded at that point, so we send
      // another here.
      sendMessage();
    });
  });
});

chrome.commands.onCommand.addListener(function(command) {
  chrome.tabs.create({url: "http://www.google.com/"});
});

chrome.runtime.onMessage.addListener(function(msg, _, sendResponse) {
  if (msg.setAlarm) {
    // For testing only.  delayInMinutes will be rounded up to at least 1 in a
    // packed or released extension.
    chrome.alarms.create({delayInMinutes: 0.1});
  } else if (msg.delayedResponse) {
    // Note: setTimeout itself does NOT keep the page awake. We return true
    // from the onMessage event handler, which keeps the message channel open -
    // in turn keeping the event page awake - until we call sendResponse.
    setTimeout(function() {
      sendResponse("Got your message.");
    }, 5000);
    return true;
  } else if (msg.getCounters) {
    sendResponse({counter: counter++,
                  persistentCounter: localStorage.counter++});
  }
  // If we don't return anything, the message channel will close, regardless
  // of whether we called sendResponse.
});

chrome.alarms.onAlarm.addListener(function() {
  alert("Time's up!");
});

chrome.runtime.onSuspend.addListener(function() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    // After the unload event listener runs, the page will unload, so any
    // asynchronous callbacks will not fire.
    alert("This does not show up.");
  });
  console.log("Unloading.");
  chrome.browserAction.setBadgeText({text: ""});
  chrome.tabs.sendMessage(lastTabId, "Background page unloaded.");
});


'Chrome Extension' 카테고리의 다른 글

A browser action with a popup that changes the page color  (0) 2015.05.02
A browser action which changes its icon when clicked  (0) 2015.05.02
Print this page  (0) 2015.04.29
Page Redder  (0) 2015.04.21
My Bookmarks  (1) 2015.04.20

다른 카테고리의 글 목록

Chrome Extension 카테고리의 포스트를 톺아봅니다