趁着2018年还剩最后几天,发几篇博客,荒废过久了,惭愧。php
最近也是需求驱动,研究了下Chrome插件开发。来看一下咱们公司运维提供的日志查看页面css
全部项目的日志都参杂在一块儿,每次去找都很痛苦。慢慢发现这些日志的名称都有个规律:项目名-日期-后缀,因而想美化下这个页面,可是服务端还动不了,只能在浏览器端想办法。前端
Chrome插件能够本地渲染页面,是个很是不错的选择,直接来看下完成的效果 jquery
按照“项目名”和“日期”分类了,这样便于查看。同时页面也美化了,不只实用并且赏心悦目。git
Chrome插件开发对环境要求极低,有一个最基本的前端开发IDE就能够了,先新建一个必须的文件:manifest.jsongithub
{ "name": "WebFileFilter", "version": "1.0.0", "description": "fast sort your webpage files", "icons": { "16": "images/icon_16px.png", "48": "images/icon_48px.png", "128": "images/icon_128px.png" }, "browser_action": { "default_icon": "images/icon_16px.png", "default_title": "WebFileFilter" }, "content_scripts": [ { "matches": [ "http://115.28.113.150:55000/log/" ], "js": [ "js/content_scripts_list.js" ], "run_at": "document_start" } ], "manifest_version": 2 }
其余属性很少说了,看看就明白。说说“content_scripts”下的“matches”节点,这个里面就是要注入js的URL地址,而“content_scripts_list.js”就是要注入的js,在“content_scripts_list.js”写一行测试代码web
console.log("hello world!");
看一下项目结构chrome
一个最基本的Chrome插件就完成了,去安装一下:打开Chrome浏览器 - 更多工具 - 扩展程序,打开“开发者模式” - 加载已解压的扩展程序 - 选择src目录 - 肯定。再刷新下页面,看看效果json
能够看到“content_scripts_list.js”已经注入这个页面了bootstrap
能够向这个页面注入js,固然也能够向这个页面注入css
{ "name": "WebFileFilter", "version": "1.0.6", "description": "fast sort your webpage files", "icons": { "16": "images/icon_16px.png", "48": "images/icon_48px.png", "128": "images/icon_128px.png" }, "browser_action": { "default_icon": "images/icon_16px.png", "default_title": "WebFileFilter" }, "content_scripts": [ { "matches": [ "http://115.28.113.150:55000/log/" ], "css": [ "css/bootstrap.min.css" ], "js": [ "js/jquery.min.js", "js/bootstrap.min.js", "js/content_scripts_list.js" ], "run_at": "document_start" } ], "manifest_version": 2 }
jQuery和Bootstrap都注入进来了,那就能够随意渲染页面了。这回“content_scripts_list.js”就不输出“hello world”了,要去获取页面原有的数据绑定到bootstrap插件上,而后去覆盖页面原来的内容,具体实现看文章结尾的源码连接。
注:“run_at”设置成“document_start”表示在原页面加载以前就注入css和js。若是不这么设置,访问页面的时候,原页面刷的一下过去再显示美化后的页面,体验较差。
同时“content_scripts_list.js”里面全部的js都须要写在document的DOMContentLoaded事件里面,不然也是达不到效果的
document.addEventListener('DOMContentLoaded', function () { //your js... });
本文以美化日志页面为例,其实适用于全部web服务器输出的文件列表页面。最近上网发现这个页面
文件名彻底符合这样的格式:分类A-分类B-分类C,因而代码都不用改,直接把这个URL地址(https://jiacrontab.iwannay.cn/download/)配置到content_scripts下的matches节点,来看下美化后的效果
Chrome插件本地源码路径,方便学习其余优秀插件的代码:
1)windows xp:C:\Documents and Settings\用户名\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions
2)windows xp+:C:\Users\用户名\AppData\Local\Google\Chrome\User Data\Default\Extensions
3)MAC:~/Library/Application Support/Google/Chrome/Default/Extensions
4)Ubuntu:~/.config/google-chrome/Default/Extensions
Chrome插件开发有不少的api,功能很是强大。这里仅抛砖引玉,更多使用场景你们本身去发挥。源码地址 Chrome商店 开发文档