原文:http://www.dahouduan/2017/08/15/chrome-extension-content-scripts/
前面两章我们介绍了弹窗 popup 和 background的用法
这篇来介绍下 conent_scripts 的用法。

Content_scripts 简介

假如你想把访问到的页面里的图片都加上好看的边框你该怎么做?

用目前学习的东西,你是无法实现这个功能的,这时候你要用到 content_scripts

使用 content_scripts 你可以修改你当前访问的页面的dom,你可以实现类似下面这样的功能:

1、放大某些特殊信息的字体
2、把页面里所有链接形式的文本都加上a 标签
3、在页面中注入HTML,为页面附加新的功能或交互
等等。

当然 content_scripts 也有一些限制,比如:

1、只能访问Chrome.extension、 Chrome.runtime 接口
2、不能直接访问它所在的扩展里的函数和变量,background里和 popup 里的都不行
看上去有些不合理,不过我们可以通过message 机制来实现content_scripts 和他所在扩展的通信,比如 background,和 popup ,从而间接实现调用扩展内部的变量和函数。

下面通过一个简单的例子来学习下 content_scripts 的用法以及它如何与自己所在的扩展进行通信。

给百度发送关键词

我们写一个例子来演示,Content_scripts 和 popup之间通信。

这个扩展主要实现了在popup.html 中向百度搜索框发送关键词,并提交搜索请求。

首先在manifest.json中添加 content_scripts 配置

{
    "name": "腾百万",
    "version": "1.0.0",
    "manifest_version": 2,
    "description": "演示content_scripts 的通信",
    "browser_action": {
        "default_title": "查看",
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    },
    "content_scripts": [
        {
            "matches": ["https://www.baidu/*"],
            "js": ["jquery-2.1.4.min.js","baidu.js"]
        }
    ],
    "permissions" : ["tabs", "activeTab"] //向浏览器申请的权限
}

content_scripts 配置块的意思是当页面 url 地址匹配到 “https://www.baidu/*” 模式时才向页面中注入jquery-2.1.4.min.js, baidu.js 两个js 文件, baidu.js 里是我们的主要的逻辑代码。

baidu.js

var kw = $('#kw');
var form = $('#form');
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.action == "send") {
            kw.val(request.keyword)
            sendResponse({state:'关键词填写成功!'});
        }
        if (request.action == "submit") {
            form.submit();
            sendResponse({state:'提交成功!'});
        }
    }
);

可以看到,在baidu.js中注册了一个监听事件,来监听popup.js 众发送过来的消息, 使用了 Chrome 提供的Chrome.runtime.onMessage 接口。

我们看 popup.html 和 popup.js 的代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="jquery-2.1.4.min.js"></script>
    <script src="popup.js">
    </script>

</head>
<body style="width:300px ;height:100px">
    <input type="keyword" id="keyword"><br />
    <span  id="state" style="color:green"></span><br />
    <button id="send">发送</button><br />
    <button id="submit">提交</button>
</body>
</html>

popup.js

$(function(){
    var state = $('#state');
    $('#send').click(function () {//给对象绑定事件
        chrome.tabs.query({active:true, currentWindow:true}, function (tab) {//获取当前tab
            //向tab发送请求
            chrome.tabs.sendMessage(tab[0].id, { 
                action: "send",
                keyword: $('#keyword').val()
            }, function (response) {
                console.log(response);
                state.html(response.state)
            });
        });
    });
    $('#submit').click(function () {
        chrome.tabs.query({active:true, currentWindow:true}, function (tab) {
            chrome.tabs.sendMessage(tab[0].id, {  
               action: "submit"   
            }, function (response) {
                state.html(response.state)
            });
        });
    })
})

到“扩展程序”界面装载上此 demo,效果如下图

(Chrome 下Gif图好像不能自动播放,右键在新窗口打开即可)
完整代码到这里找:
https://github/shanhuhai/Chrome-extension-demo/tree/master/Lesson-3-content_scripts

把程序的主要逻辑讲下,首先我们的 baidu.js 就是属于 content_scripts, 只要打开的是百度的(url 匹配了 https://www.baidu/*)页面,在 baidu.js 中就可以操作页面dom,我们在baidu.js 中注册了一个监听事件来监听popup.js发送过来的消息,如果action=”keyword”, 就把发送过来的关键字用 jquery 的方法设置到百度的搜索框中,点击“提交”按钮,相当于是触发百度搜索里的“百度一下”按钮。

由于是系列教程,对于一些概念的叫法不明白请翻看前面两篇:

Chrome 扩展开发教程(1) ——Hello Chrome
Chrome 扩展开发教程(2) ——Background的用法

好了,这个简单的例子就讲到这里了,后面该讲什么还没想好,下篇再说。88

更多推荐

Chrome 扩展开发教程(3)——content_scripts用法