插件的主要文件,描述插件的信息、权限、脚本等,和uniapp的manifest.json文件类似
json{
"manifest_version": 2,
"name": "My First Extension",
"description": "This is a sample Chrome Extension",
"version": "1.0",
/*插件的图标*/
"icons": {
"48": "icon.png",
"128": "icon_large.png"
},
/*需要申请的权限*/
"permissions": [
"activeTab",
"storage",
"https://*.mywebsite.com/*"
],
/*后端运行脚本,随浏览器加载*/
"background": {
"scripts": ["background.js"],
"persistent": false
},
/*内容脚本*/
"content_scripts": [
{
"matches": ["https://*.google.com/*"],
"js": ["content.js"],
"run_at": "document_end"
}
],
/*插件显示在浏览器工具栏的信息*/
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Open the popup"
},
/*插件配置页*/
"options_page": "options.html",
/**/
"web_accessible_resources": [
"script.js",
"style.css"
]
}
javascript// background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
code: 'document.body.style.backgroundColor="green"'
});
});
javascript// content.js
window.onload = function() {
var links = document.getElementsByTagName('a');
for(var i = 0; i < links.length; i++) {
links[i].style.color = 'red';
}
};
html<!-- popup.html -->
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to My Extension!</h1>
</body>
</html>
html<!-- options.html -->
<!DOCTYPE html>
<html>
<body>
<h1>Extension Options</h1>
<label>Background color: <input type="text" id="bgColor"></label>
<button id="save">Save</button>
<script src="options.js"></script>
</body>
</html>
javascript// options.js
document.getElementById('save').onclick = function() {
var color = document.getElementById('bgColor').value;
chrome.storage.sync.set({backgroundColor: color});
};
javascriptchrome.runtime.onStartup.addListener(function() {
console.log("Browser has been started.");
});
javascriptchrome.windows.onRemoved.addListener(function(windowId) {
chrome.windows.getAll({}, function(windows) {
if(windows.length == 0) {
console.log("Browser is closing, the last window was closed.");
}
});
});
chrome.windows.onCreated.addListener(function() { console.log("New window opened."); });
javascriptchrome.windows.onRemoved.addListener(function(windowId) {
console.log("Window with id " + windowId + " was closed.");
});
javascriptchrome.tabs.onActivated.addListener(function(activeInfo) {
console.log("Tab with id " + activeInfo.tabId + " is now active.");
});
在浏览器的扩展管理页面,打开开发人员模式,选择“加载解压缩的扩展”进行开发,修改代码以后刷新页面即可看到效果。
javascriptchrome.tabs.create({url: "http://www.example.com"});
javascriptchrome.bookmarks.create({
'parentId': '1',
'title': 'Extension bookmarks',
'url': 'http://www.example.com'
});
javascriptchrome.notifications.create({
type: 'basic',
iconUrl: 'icon.png',
title: 'Notification title',
message: 'Notification message'
});
javascript// 保存数据
chrome.storage.sync.set({ key: value }, function() {
console.log("Data saved.");
});
// 读取数据
chrome.storage.sync.get("key", function(result) {
console.log("Data retrieved: ", result.key);
});
本文作者:谭三皮
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!