通过Chrome扩展读取网站内容,可以实现自动爬取数据,自动化测试。
核心开发流程
sequenceDiagram
扩展页面->>扩展页面:触发动作
扩展页面->>监听脚本:发送执行命令
监听脚本-->>监听脚本:监听执行命令
监听脚本-->>监听脚本:执行命令,操作网页DOM
监听脚本-->>扩展页面:返回执行结果
扩展页面->>扩展页面:响应执行结果
上代码
1. 新建项目(文件夹)demo,定义manifest.json
{
"name": "Demo小工具",
"description" : "扩展小工具",
"version": "1.0",
"manifest_version": 2,
"browser_action": {
"default_popup": "index.html", // 点击扩展弹出的页面
"default_icon": "bbb.png" // 扩展logo
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["listener.js"] // 监听脚本
}
],
"permissions": ["*://*/*","tabs"] // 赋予权限
}
2. 编写扩展页面,可以引用JQuery库
<html>
<head>
<title>hello world</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body style="width: 100px;height: 100px;">
<button id="me" href="#">立刻获取页面元素</button>
<!-- 也可以引用JQuery -->
<script src="jquery-1.7.1.min.js"></script>
<script>
$('#me').live('click', function() {
chrome.tabs.getSelected(null, function (tab) {
//向tab发送执行动作
chrome.tabs.sendRequest(tab.id, { action: "hello" }, function (response) {
// 响应执行结果
alert(response.content);
});
});
});
</script>
</body>
</html>
3. 编写监听脚本
chrome.extension.onRequest.addListener(//监听扩展程序进程或内容脚本发送的请求
function (request, sender, sendResponse) {
if (request.action == "hello") { // 执行动作
sendResponse({ content: document.title });
}
}
);
4. 安装扩展
Chrome 浏览器右上角 / 更多工具 / 扩展程序 / 加载已解压的扩展程序