今天由于老板要求写了一个现学一个谷歌插件的用法,记录一下;
首先最主要的就是manifest.json文件;
看一下我这个简单的配置:
- manifest.json
{
// 插件名称
"name": "美丽的插件",
// 版本号
"version": "1.0",
"manifest_version": 2,
"content_scripts": [
{
// 在什么url中执行js的内容
"matches": [
"http://www.baidu.com/*"
],
"js": [
"index.js"
]
}
],
// 是允许打开新的tab
"permissions": [
"tabs"
],
"browser_action": {
// 这是在右上角插件的图标
"default_icon": "libai.png"
},
// 这是在插件管理页面显示的图标内容
"icons": {
"16": "libai.png",
"48": "libai.png"
},
"background": {
"scripts": [
"background.js"
]
}
}
其中background和browser_action两者根据不同的需求写出不同的内容,background中是一全屏为内容显示的,而default_popup则是显示在浏览器的右上角。
- index.js
alert(<div><a href="http://www.baidu.com">百度</a>
<a href="http://www.google.com/">谷歌</a>
<a href="https://cn.bing.com/">bing</a>
<a href="http://www.baidu.com">百度</a>
<a href="http://www.google.com/">谷歌</a>
<a href="https://cn.bing.com/">bing</a></div>);
- background.js
// 谷歌监听并打开新的页面
chrome.browserAction.onClicked.addListener(function () {
chrome.tabs.create({ url: "popup.html" }, function (tab) {
console.log(tab)
});
})
- popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
span {
white-space: nowrap;
color: #fff;
font-size: 20px;
background: linear-gradient(to right, red, purple);
}
</style>
</head>
<body>
<a href="./views/baidu.html">百度</a>
<a href="./views/guge.html">谷歌</a>
<a href="./views/bing.html">bing</a>
<script src="./popup.js"></script>
</body>
</html>
- popup.js
执行popup.html中的内容,这一点需要注意的是popup.js的内容不支持直接写在html文件中的,也就是html文件中不允许出现js内容。
let a = document.querySelectorAll('a');
function sleep(time, i) {
return new Promise(res =>
setTimeout(res, time)
)
}
async function main() {
for (let i = 0; i < a.length; i++) {
console.log(i)
let popup = window.open(',');
popup.location.href = a[i].href;
setTimeout(() => {
popup.close();
}, 5000)
await sleep(5000, i)
}
}
main();