平时用ad这些谷歌浏览器拦截插件,觉得挺有意思的,就萌发写一个浏览器插件。
文章目录
前言
本来以为会挺难的,其实也不是,多看官方文档就行提示:以下是本篇文章正文内容,下面案例可供参考
一、我的第一个插件
用过firefox浏览器的都知道,有一个把当前页面的url生成二维码给手机扫描的功能
如图:
我的第一个插件决定就做它了。
效果:
项目结构:
二、how to do
1. 最简单的插件
新建文件夹,目录下建manifest.json
文件
{
"name": "urlToQRCode",
"version": "1.0",
"description": "a chrome extension which make tab url to qrcode for user scan by their phone",
"manifest_version": 2,
}
"icons": { "128": "qrcode128.png" },
注意manifest_version 须大于2,
icons可选,大小最后选128x128
2. 浏览器加载插件
打开开发者模式,点击加载已解压的扩展程序。选择你刚才的目录。你的第一个插件就已经完成了。
3. browser_action
在manifest.json增加下面字段
{
"name": "urlToQRCode",
"version": "1.0",
"description": "a chrome extension which make tab url to qrcode for user scan by their phone",
"manifest_version": 2,
"icons": { "128": "qrcode128.png" },
"browser_action": {
"default_icon": "qrcode.png",
"default_title": "点击生成当前页面二维码",
"default_popup": "popup.html"
},
"permissions": [
"http://*/",
"https://*/*",
"tabs",
"activeTab"
]
}
就是点击显示popup.html 。
4. popup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="popup.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div id="qrcode"></div>
<span id="info">扫一扫,直接在手机上打开</span>
</div>
</body>
<script text="text/javascript" src="qrcode.js"></script>
<script text="text/javascript" src="popup.js"></script>
</html>
新建:popup.css
.container {
display: flex;
display: -webkit-flex;
flex-direction: column;
align-items: center;
width: 300px;
height: 300px;
justify-content: center;
border-radius: 5px;
}
#info {
margin-top: 5px;
font-size: 20px;
}
引入qrcode.js 这是个开源项目,可在https://github.com/davidshimjs/qrcodejs,获得,或者本项目gitee中获取:https://gitee.com/yu_sheng_sheng/tab-url-to-qrcode-chrome-extension
同目录建popup.js
,
window.onload = function() {
chrome.tabs.query({ active: true, windowId: chrome.windows.WINDOW_ID_CURRENT }, (res) => {
var qrcode = new QRCode(document.getElementById("qrcode"), {
width: 200,
height: 200
});
qrcode.makeCode(res[0].url);
})
}
注意不可在popup.html 使用行内样式或者js脚本,官方要求。
chrome.tabs.query 官方api 作用是获取tab,
5. permissions
所需要的权限。这里用到tab
全部弄好刷新
该插件就完成了。
项目地址
https://gitee.com/yu_sheng_sheng/tab-url-to-qrcode-chrome-extension
总结
这里只是简单的功能,
复杂的还有两个字段content_script 和background ,
把这三个popup.html, content_script ,background api看懂,并且三者通信搞懂,基本可以没啥插件你不会开发了。
- popup.html: 用户点击后展示页面,插件使用者使用
- content_script.js: 插入脚本到浏览器当前页面
- background.js:插件后台,可与你的服务器交互
下一个插件:模仿firefox 的取色器。