简单chorme插件编写例子源码
时间: 2023-09-02 10:04:27 浏览: 57
以下是一个简单的Chrome插件编写例子的源码:
manifest.json文件内容:
```
{
"manifest_version": 2,
"name": "My First Chrome Extension",
"version": "1.0",
"description": "一个简单的Chrome插件示例",
"permissions": [
"activeTab"
],
"browser_action": {
"default_popup": "popup.html"
},
"icons": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["content.js"]
}
]
}
```
popup.html文件内容:
```
<!DOCTYPE html>
<html>
<head>
<title>My First Chrome Extension</title>
<style>
body {
width: 300px;
height: 200px;
font-family: Arial, sans-serif;
font-size: 14px;
}
h1 {
text-align: center;
}
#btnClick {
width: 100px;
height: 30px;
margin: 0 auto;
display: block;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Welcome to My Chrome Extension</h1>
<button id="btnClick">Click Me</button>
<script src="popup.js"></script>
</body>
</html>
```
popup.js文件内容:
```
document.addEventListener("DOMContentLoaded", function() {
var btnClick = document.getElementById("btnClick");
btnClick.addEventListener("click", function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {action: "show_notification"}, function(response) {
console.log(response);
});
});
});
});
```
background.js文件内容:
```
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === "show_notification") {
var notificationOptions = {
type: "basic",
iconUrl: "icon.png",
title: "消息通知",
message: "这是一条来自插件的通知!"
};
chrome.notifications.create("", notificationOptions, function(notificationId) {
sendResponse(notificationId);
});
}
return true;
});
```
content.js文件内容:
```
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === "show_notification") {
alert("插件发送的通知!");
sendResponse("通知已显示");
}
});
```
这个例子实现了一个简单的Chrome插件,当我们在浏览器中点击插件图标的按钮时,会向当前激活的标签页发送一个消息,然后在标签页中弹出一个通知。