Chrome插件开发实例 – 开关灯(browser action)

这里通过一个网页开关灯的例子来演示browser action,除了browser action之外,还会涉及到其他很多的chrome api或者manifest.json配置项。

20130614000050

这个文件包含的文件如下:
background.html

背景页,一个单独的长时间运行的脚本,是一个运行在扩展程序中的html页面。在应用的整个生命周期都存在,在同一个时间只有一个实例处于活动状态。

background.js

背景页的JS,一般不需要上面的background.html也可以,manifest.json中按照如下配置就可以了:

"background": {
          "scripts": ["background.js"]
      }
func.js

一个需要注入到页面中的 content script

icon.png

应用的图标 19px * 19px

jquery-2.0.2.js

需要注入页面中使用的jquery库

manifest.json

应用的配置文件

popup.html

点击浏览器工具栏时,应用的弹窗页面

popup.js

弹窗页面对应的JS文件,在popup.html中引入。

下面就逐个文件说明:
manifest.json
{
    "manifest_version": 2,
      "name": "pv show",
      "description": "__MSG_ext_desc__",
      "version": "2",
      "default_locale": "en",
      "icons": {
        "48": "images/icon_16.png",
        "48": "images/icon.png",
        "128": "images/icon_128.png"
       },
      "permissions": [
        "tabs", 
        "http://*/*", 
        "https://*/*", 
        "notifications"
      ],
      "browser_action": {
           "default_icon": "images/icon.png",
           "default_popup": "options.html",
        "default_title": "网页流量统计"
      },
      "background": {
          "scripts": ["background.js"]
      }
}
popup.html
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>开关灯</title>
        <style>
            div{
                width:100px;
                height:20px;
                line-height:20px;
                text-align:center;
                font-family: sans-serif;
                font-size:0.8em;
                background:#F3F3F3;
                margin-bottom:4px;
                cursor:pointer;
            }
            div:hover{
                background:#CCCCCC;
            }
            .day{
                background:#000;
            }
            .night{
                background:#FFF;
            }
        </style>
        <!-- 引入JS文件,这里引入的文件只能在popup.html页面中使用,不能再web页面中使用(页面中的为content script) -->
        <script src="popup.js"></script>
        <script src="jquery-2.0.2.min.js"></script>
    </head>
    <body>
        <div id="off">关灯</div>
        <div id="on">开灯</div>
    </body>
</html>
popup.js
/*
 * 
 * 这个JS文件表示对popup.html文档的操作
 * 比如直接在这里写的document也是代表了popup.html的文档流
 */

// 这里的document代表了popup.html的文档流,所以也是注册这个页面中的dom事件
document.addEventListener('DOMContentLoaded', function(){
    var divs = document.querySelectorAll('div');
    var obj = {"name":"root", "password":"123"};
    for(var i=0; i<divs.length; i++){
        divs[i].addEventListener('click', function(e){
            // var jsonText = JSON.stringify(e);  // 转换报错
            // console.log(jsonText);
            // chrome.tabs.executeScript(null,
            //     {code:"switchLight('"+ obj +"');", allFrames: true}); // 这里如果传递一个e事件对象的话,会自动转换为字符串字面值,导致对象变成了字符串
            // 向页面注入JavaScript 脚本执行,由于这里调用的是一个JS方法switchLight(),该方法在func.js文件中,所以可以在background.js中把该JS(content script)注入到web页面中。
            chrome.tabs.executeScript(null,
                 {code:"switchLight('"+ e.target.id +"');", allFrames: true});
            // console.log("send");
            // chrome.extension.sendRequest(e);   // 发送请求方法可以传递JSON对象,但是这里chrome把e事件对象转换为JSON字符串时会报错:Uncaught TypeError: Converting circular structure to JSON
        });        
    }
});
func.js
// 一个简单的方法直接设置document.body的背景颜色,即开关灯效果
// 由于这个content script是注入到web页面中的,所以这里的document也就是代表web页面中的文档
function switchLight(lightAction){
    console.log(lightAction);
    if(lightAction == 'off'){
        document.body.style.backgroundColor='#000';
    } else {
        document.body.style.backgroundColor='#fff';
    }
}
background.html

背景页,应用的整个生命周期都存在,这个页面只是简单的引用了background.js文件,不用也可以,见上面的说明。

<html>
<head>
<script src="background.js"></script>
</head>
<body>
</body>
</html>
bakcground.js
/**
 * 注册标签页更新时的事件
 * 这里调用了initialize()事件,把func.js注入当前标签页中 
 */
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    initialize(tabId);
});

/**
 * 注册切换标签页时的事件
 * 这里调用了initialize()事件,把func.js注入当前标签页中
 */
chrome.tabs.onSelectionChanged.addListener(function(tabId, selectInfo) {
    initialize(tabId);
});

/**
 * 初始化方法 ,注入func.js事件
 * @param {Object} tabId
 */
function initialize(tabId){
    chrome.tabs.executeScript(tabId, {file: "func.js", allFrames: true});
    chrome.tabs.executeScript(tabId, {file: "jquery-2.0.2.js", allFrames: true});
}

/**
 * 启动一个chrome.extension.onRequest事件监听器用来处理消息
 */
chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    chrome.tabs.executeScript(null, {code: "switchLight("+ request +");", allFrames: true});
});

源代码稍后补充...

关键字:  Chrome插件
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值