前言
- 閲讀本文,可以自己寫一個簡單的瀏覽器插件
- 以及前端瀏覽器插件相關東西
- 附上github源碼:https://github.com/shuirongshuifu/browser-plugin
- 接下來學學這個不常用的知識點吧...
效果圖
- 我們先看一下,自己手寫的簡單插件的操作效果圖(點擊彈出時間)
拓展程序部分
或者地址欄輸入:chrome://extensions/ 回車直接訪問
代碼
manifest.json
manifest.json用了記錄這個瀏覽器插件的相關信息
{
"manifest_version": 2,
"name": "點擊獲取當前的時間", // 插件名字
"version": "1.0", // 插件版本
"description": "這個插件可用於獲取當前的年月日時分秒", // 關於這個插件的介紹
"browser_action": {
"default_popup": "popup.html", // 這個插件使用的彈出層的html
"default_icon": { // 這個插件固定在插件欄的圖標(不同尺寸可以使用不同的圖片)
"16": "icon.png",
"32": "icon.png",
"48": "icon.png",
"128": "icon.png"
}
},
"icons": { // 插件卡片使用的圖標(就是拓展中的插件卡片那個地方)
"16": "logo.png",
"32": "logo.png",
"48": "logo.png",
"128": "logo.png"
},
"permissions": [
"activeTab" // 激活的tab用
],
"content_scripts": [ // 往內容中注入腳本
{
"matches": [
"<all_urls>" // 針對於所有的地址都用
],
"js": [
"inject.js" // 注入的js腳本的文件名
]
}
]
}
popup.html
給點擊這個插件的彈出層,來一個簡單的html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>time</title>
<style>
body {
text-align: center;
}
#clock {
font-size: 32px;
font-weight: bold;
background-color: #eee;
color: rgb(157, 81, 215);
box-sizing: border-box;
padding: 12px;
border-radius: 6px;
}
</style>
</head>
<body>
<div id="clock"></div>
<script src="popup.js"></script>
</body>
</html>
popup.js
這裏拆分出來js文件,當然也可以使用script標籤,丟在一塊
function updateClock() {
const clockElement = document.querySelector('#clock')
const currentTime = new Date();
clockElement.textContent = currentTime.toLocaleString();
}
setInterval(updateClock, 1000);
inject.js
簡單注入一個腳本,如下圖:
// inject.js文件
console.log('直接注入的腳本內容,頁面一加載就執行,要先打開F12控制枱看哦');
目錄結構圖:
未完待續...
參考文章
更多功能細節點,請見下方參考
- 知乎文:https://zhuanlan.zhihu.com/p/678535335
- 官方文檔360團隊翻譯:https://wizardforcel.gitbooks.io/chrome-doc/content/index.html