要从网页获取信息,您可以使用Chrome扩展来注入自定义JavaScript代码。以下是一个简单的示例,展示了如何创建一个Chrome扩展来获取网页上的信息。
my-extension
。manifest.json
content.js
manifest.json
manifest.json
是扩展的配置文件,它告诉Chrome扩展的结构和权限。
{
"manifest_version": 3,
"name": "My Extension",
"version": "1.0",
"description": "A simple extension to fetch information from web pages.",
"permissions": [
"activeTab"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/icon16.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
}
},
"icons": {
"16": "images/icon16.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
}
}
content.js
content.js
是注入到网页中的JavaScript代码,用于获取信息。
// content.js
document.addEventListener('DOMContentLoaded', () => {
const elements = document.querySelectorAll('.target-element'); // 替换为你要选择的元素选择器
const data = [];
elements.forEach(element => {
data.push(element.innerText);
});
// 将数据发送到background.js
chrome.runtime.sendMessage({ data: data });
});
background.js
background.js
处理从 content.js
发送过来的数据。
// background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.data) {
console.log('Fetched data:', request.data);
// 这里可以处理数据,例如发送到popup.html或存储到本地存储
}
});
popup.html
popup.html
是扩展的弹出窗口,用于显示获取的信息。
<!DOCTYPE html>
<html>
<head>
<title>My Extension</title>
<style>
body {
width: 200px;
padding: 10px;
}
#data {
white-space: pre-wrap;
}
</style>
</head>
<body>
<h1>Fetched Data</h1>
<div id="data"></div>
<script src="popup.js"></script>
</body>
</html>
popup.js
popup.js
处理从 background.js
发送过来的数据并在弹出窗口中显示。
// popup.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.data) {
document.getElementById('data').innerText = JSON.stringify(request.data, null, 2);
}
});
chrome://extensions/
进入扩展管理页面。my-extension
文件夹。.target-element
)正确匹配你要获取信息的网页元素。领取专属 10元无门槛券
手把手带您无忧上云