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

原文:http://www.dahouduan.com/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.com/*"],
            "js": ["jquery-2.1.4.min.js","baidu.js"]
        }
    ],
    "permissions" : ["tabs", "activeTab"] //向浏览器申请的权限
}

content_scripts 配置块的意思是当页面 url 地址匹配到 “https://www.baidu.com/*” 模式时才向页面中注入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.com/shanhuhai/Chrome-extension-demo/tree/master/Lesson-3-content_scripts

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

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

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

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

Chrome扩展content-scripts请求跨域的问题,可以通过在manifest.json文件中添加"permissions"和"web_accessible_resources"字段来解决。具体步骤如下: 1. 在manifest.json文件中添加"permissions"字段,用于声明扩展需要访问的权限。例如: ``` { "name": "My Extension", "version": "1.0", "manifest_version": 2, "permissions": [ "http://www.example.com/*" ], "content_scripts": [ { "matches": ["http://www.example.com/*"], "js": ["content_script.js"] } ] } ``` 以上代码中,"http://www.example.com/*"表示扩展需要访问的域名,"content_scripts"表示扩展需要注入的脚本。 2. 在manifest.json文件中添加"web_accessible_resources"字段,用于声明扩展需要访问的资源。例如: ``` { "name": "My Extension", "version": "1.0", "manifest_version": 2, "permissions": [ "http://www.example.com/*" ], "content_scripts": [ { "matches": ["http://www.example.com/*"], "js": ["content_script.js"] } ], "web_accessible_resources": [ "http://www.example.com/*" ] } ``` 以上代码中,"http://www.example.com/*"表示扩展需要访问的资源。 3. 在content_script.js文件中使用XMLHttpRequest或fetch等API发送跨域请求,代码示例如下: ``` fetch('http://www.example.com/api/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); ``` 以上代码中,fetch方法用于发送跨域请求,并且在响应中获取数据。 需要注意的是,如果要在content-scripts中使用cookie等认证信息,需要在manifest.json文件中添加"permissions"字段,并使用XMLHttpRequest或fetch等API发送带有cookie的跨域请求。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值