今天的30天挑戰,我決定學習怎樣開發谷歌擴展,一番搜索後,我找到一個Yeoman Generator用於開發谷歌擴展。本文要寫的擴展會在工做時間阻止咱們登錄FaceBook, Twitterm LinkdIn和其餘社交網站,這裏再也不闡述Yeoman基礎知識,你能夠參考第24天博客瞭解Yemoman基礎。css
咱們來寫一個很簡單的擴展,在上班時間按(9am-6pm)阻止咱們登錄社交網站如Facebook, Twitter等,若是用戶想登錄那些網站,會看到如圖頁面。html
Google+ 沒有被阻止 :) git
輸入如下命令安裝yeoman, 前提假設你已經安裝Node和NPM.github
$ npm install -g yeoman
以上命令會全局安裝yeoman, -g 用於標識全局安裝,同時若是你還沒安裝Grunt,這個命令會幫你裝上。 web
Yeoman依賴Generators來架構程序代碼,流行JavaScript MV* 框架有多種generator, 本文咱們用Chrome genterator.chrome
NPM用於裝generators.npm
$ npm install -g generator-chrome-extension
今天的demo在 github: day29-chrome-extension. json
基礎講完,如今來開發擴展程序。 數組
在你本地機爲擴展新建一個目錄,並把當前路徑指向這個目錄。架構
$ mkdir no-socializing
$ cd no-socializing
而後運行yo chrome-extension, 它會問你如圖幾個問題。
一個個來看這些問題。
你能夠安裝沒有打包的擴展到Chrome, 如圖,勾上Developer Mode, 點擊Load unpackaged extension, 在no-socializing路徑下添加app文件夾。
Chrome擴展行爲指定在app/scripts文件夾下的background.js, 複製粘貼如下代碼到background.js.
'use strict'; chrome.webRequest.onBeforeRequest.addListener( function(details) { var currentTime = new Date(); if(isOfficeTime(currentTime) && isWeekday(currentTime)){ return {redirectUrl: chrome.extension.getURL('index.html')}; } return details.url; }, { urls: [ "*://*.facebook.com/*", "*://*.twitter.com/*", "*://*.gmail.com/*", ], types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"] }, ["blocking"] ); function isOfficeTime(currentTime){ var hour = currentTime.getHours(); return hour > 9 && hour < 18; } function isWeekday(currentTime){ var dayOfWeek = currentTime.getDay(); return dayOfWeek >= 1 && dayOfWeek <= 5; }
以上代碼:
監聽onBeforeRequest事件,當有請求出現時鎖定目標,addListener功能有三個參數。
同時也定義了幾個功能用於查詢當前時間和星期,只在工做日的9am-6pm禁止使用社交網站。
以上代碼使用WebRequest API, 咱們須要給這個擴展訪問chrome.webRequest API, 使用webRequest權限能夠完成。因爲這個擴展在阻止方法中用chrome.webRequest API,咱們也須要給webRequestBlocking權限,在app路徑下打開manifest.json, 更新權限部分。
"permissions": [ "webRequest", "tabs", "http://*/*", "https://*/*", "webRequestBlocking" ]
最後須要添加index.html, 它會在用戶請求訪問Facebook, Twitter等時加載。
<!DOCTYPE html> <html lang="en"> <head> <title>No Socializing</title> <link rel="stylesheet" href="/styles/main.css"> </head> <body> <h1>NO, Socializing</h1> <img src="/images/no-social-media.jpg" height="450" width="450"> <h2>It's Office Time Dude</h2> </body> </html>
你能夠從 github倉庫下載圖片。
從新加載擴展,訪問 http://facebook.com 或者 http://twitter.com, 若是如今是9am-6pm,能夠看到如圖。
這就是今天的內容,繼續給反饋吧。