Total Pageviews

2016/12/05

[Chrome Extension] Create a simple chrome extenstion with AngularJS 1.X

The steps are as bellows:

1. Download AngularJS 1 from https://angularjs.org/

2. Download Bootstrap from https://getbootstrap.com/

3. Create manifest.json
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{
  "manifest_version": 2,
  "name": "Build Chrome Extension With AngularJS",
  "description": "利用 AngularJS 建置 Chrome Extension ",
  "version": "1.0",
  "permissions": [ "activeTab" ],
  "browser_action": {
    "default_icon": "img/icon.png",
    "default_popup": "todo.html",
    "default_title": "Build Chrome Extension With AngularJS"
  }
}

4. Create popup window
 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
<!DOCTYPE html>
<html style="min-width:220px;">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Todo list Page</title>
        <script src="js/angular.min.js"></script>
        <script src="js/todo.js"></script>
        <script src="js/bootstrap.min.js"></script>
        <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
    </head>

    <body>
        <div ng-app="todoApp" ng-controller="todoController" class="container">
            <form id='myForm'>
                <div class="row">
                    <input type="text" ng-model="task">
                    <button class="btn btn-primary btn-xs" ng-click="addTask()">
                        <i class="glyphicon glyphicon-plus"></i>
                    </button>
                </div>               
            </form>

            <div class="row">
                <ul>
                    <li ng-repeat="t in tasks track by $index">{{ t }} 
                        <button class="btn btn-default btn-xs" ng-click="deleteTask()">
                            <i class="glyphicon glyphicon-minus"></i>
                        </button>
                    </li>
                </ul>
            </div>
            
        </div>
    </body>
</html>


5. Create a JS file for popup window
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
angular.module('todoApp', [])
    .controller('todoController', function($scope) {

        $scope.tasks = [];
        
        $scope.addTask = function() {
            if(isNotEmptyOrUndefined($scope.task)){
                 $scope.tasks.push($scope.task);
                $scope.task = '';
            } else {
                alert('task name cannot be null');
            }           
        }
        
        $scope.deleteTask = function() {
            $scope.tasks.splice(this.$index, 1);
        }

});

// 檢查是串是否不為空值且不為undefined
function isNotEmptyOrUndefined(str) {
    return str != '' && !angular.isUndefined(str) && str != null;
}


6. Install to Chrome and do test


Source code: https://github.com/junyuo/ChromeExtensions/tree/master/ChromeExtensionWithAngular

No comments: