Chrome扩展开发学习笔记之扩展基础

来源:互联网 发布:秉钧网络 编辑:程序博客网 时间:2024/05/17 20:30

扩展的基本属性

通过Chrome扩展我们可以对用户当前浏览的页面进行操作,实际上就是对用户当前浏览页面的DOM进行操作。通过Manifest中的content_scripts属性可以指定将哪些脚本何时注入到哪些页面中,当用户访问这些页面后,相应脚本即可自动运行,从而对页面DOM进行操作。

Manifest的content_scripts属性值为数组类型,数组的每个元素可以包含以下元素:

  • matches - 哪些页面会被注入脚本
  • exclude_matches - 哪些页面不会被注入脚本
  • css - 注入css样式
  • js - 注入JavaScript代码
  • run_at - 何时注入
  • all_frames - 脚本是否会注入到嵌入式框架中
  • include_globsexclude_globs - 全局URL匹配

最终脚本是否会被注入由matchesexclude_matchesinclude_globsexclude_globs的值共同决定。

简单的说,如果URL匹配mathces值的同时也匹配include_globs的值,会被注入;如果URL匹配exclude_matches的值或者匹配exclude_globs的值,则不会被注入。

扩展编写

下面我们来写一个恶作剧的小扩展,女生都喜欢买买买!!!每天都会逛淘宝、京东之类的商城,现在简单的以淘宝为例,让他们永远点不到搜索按钮,名字就叫做再买就剁手吧 :)

创建Manifest文件

{    "manifest_version": 2,    "name": "永远点不到的搜索框",    "version": "1.0",    "description": "让你永远也点击不到淘宝搜索框",    "content_scripts": [{    "matches": ["*://www.taobao.com/"],    "js": ["js/cannot_touch.js"]    }],    "browser_action": {        "default_icon": {        "19": "images/icon19.png",        "38": "images/icon38.png"        }    },    "icons": {        "16": "images/icon16.png",        "48": "images/icon48.png",        "128": "images/icon128.png"    }}

content_scripts属性中我们定义了一个匹配规则,当URL符合*://www.taobao.com/规则的时候,就将js/cannot_touch.js注入到页面中。其中*代表任意字符,这样当用户访问http://www.taobao.com/https://www.taobao.com/时就会触发脚本。

右键单击搜索按钮,选择“审查元素”,我们发现淘宝搜索框的id为’J_TSearchForm’。

编写cannot_touch.js

搜索框ID

右键单击搜索按钮,选择“审查元素”,我们发现Google搜索按钮的id为’J_TSearchForm’。

function btn_move(el, mouseLeft, mouseTop){    var leftRnd = (Math.random()-0.5)*20;    var topRnd = (Math.random()-0.5)*20;    var btnLeft = mouseLeft+(leftRnd>0?100:-100)+leftRnd;    var btnTop = mouseTop+(topRnd>0?30:-30)+topRnd;    btnLeft = btnLeft<100?(btnLeft+window.innerWidth-200):(btnLeft>window.innerWidth-100?btnLeft-window.innerWidth+200:btnLeft);    btnTop = btnTop<100?( btnTop+window.innerHeight-200):(btnTop>window.innerHeight-100?btnTop-window.innerHeight+200:btnTop);    el.style.position = 'fixed';    el.style.left = btnLeft+'px';    el.style.top = btnTop+'px';}function over_btn(e){    if(!e){    e = window.event;    }    btn_move(this, e.clientX, e.clientY);}document.getElementById('J_TSearchForm').onmouseover = over_btn;

运行界面

  • 扩展运行的结果

代码运行可能有点bug,但不是我们关心的问题,这个扩展的源码可以在 https://github.com/lanceWan/chrome-plugin/tree/master/Note02 下载到。

本文同步地址:http://www.iwanli.me

0 0