请给一个 chrome 插件,点击按钮填充输入框
时间: 2024-10-24 13:08:43 浏览: 25
淘宝自动登录chrome插件
4星 · 用户满意度95%
一个简单的Chrome插件示例,可以设计成点击按钮后自动填充预设文本到指定的输入框。首先,你需要准备以下几个组件:
1. manifest.json:
```json
{
"manifest_version": 2,
"name": "Text Filler",
"version": "1.0",
"permissions": ["activeTab", "storage"],
"background": {"scripts": ["background.js"]},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
```
2. background.js (后台脚本):
```javascript
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.sendMessage(tab.id, { action: 'fillText', text: 'Predefined Text' });
});
```
3. popup.html (弹窗):
```html
<!DOCTYPE html>
<html>
<body>
<button id="fillButton">Fill Input</button>
<script src="popup.js"></script>
</body>
</html>
```
4. popup.js (弹窗脚本):
```javascript
document.getElementById('fillButton').addEventListener('click', function() {
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
chrome.tabs.executeScript(
tabs[0].id,
{ code: 'document.querySelector("[data-fill-field]").value = arguments[0].text;' },
function(response) {}
);
});
});
```
5. content.js (内嵌脚本,用于接收消息并找到目标输入框):
```javascript
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.action === 'fillText') {
var inputField = document.querySelector('[data-fill-field]');
if (inputField) {
inputField.value = request.text;
} else {
console.error("No field found with data-fill-field attribute");
}
}
},
{ matchPattern: "<all_urls>" }
);
```
阅读全文