1.目录结构如下:

淘宝浏览器插件排行(浏览器插件开发)(1)

2.manifest.json文件代码如下:

{ "description": "抓取页面数据", "manifest_version": 2, "name": "抓数", "version": "1.0", "icons": { "48": "icon/data_48.png" }, "browser_action": { "default_icon": { "48": "icon/data_48.png" }, "default_title": "抓数", "default_popup": "popup/index.html" }, "content_scripts": [ { "matches": [ "*://*.taobao.com/*" ], "js": [ "scripts/jquery-3.4.1.min.js", "scripts/index.js" ] } ], //向浏览器申请的权限 "permissions": [ "tabs", "activeTab" ] }

3.content_scripts的相关脚本如下(匹配matches的网址会自动加载对应的js的配置的脚本):

//scripts/index.js $(function () { // https://blog.csdn.net/qq_21859119/article/details/78805877 $('body').append("<div>9999</div>"); var list = $("#J_NavCommonRowItems_0").find("a").map(function (index, item) { return item.innerText; }); console.log(list) var title = $("#J_NavCommonRow_0 .title")[0].innerText; console.log(title); chrome.runtime.onMessage.addListener( function (request, sender, sendResponse) { //request可以接收browser_action页面的js发送过来的数据 if (request.action == "send") { //发送给browser_action的数据 sendResponse({state: title ''}); } if (request.action == "submit") { sendResponse({state: title, list: Array.from(list)}); } } ); })

4.browser_action的相关脚本如下(点击浏览器插件时的弹出层):

//popup/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="index.css"/> </head> <body> <form action="http://www.baidu.com" method="post"> <dl> <dd><label for="title">标题</label><input id="title" name="title" type="text"/></dd> <dd><label for="sellCount">品牌类型</label><input id="sellCount" name="sellCount" type="text"/></dd> <dd><label for="storeCount">品牌数量</label><input id="storeCount" name="storeCount" type="text"/></dd> <button id="submit">提交表单</button> </dl> </form> </body> <script type="application/javascript" src="../scripts/jquery-3.4.1.min.js"></script> <script type="application/javascript" src="index.js"></script> </html>

//popup/index.js $(function () { console.log(11) $('#submit').click(function () { chrome.tabs.query({active: true, currentWindow: true}, function (tab) { chrome.tabs.sendMessage(tab[0].id, //发送给content_script的数据 { action: "submit" }, function (response) { //response可以接收content_script发送过来的数据 $("#title").val(response.state); $("#sellCount").val(response.list); $("#storeCount").val(response.list.length); console.log(response.list.join(',')) }); }); }) })

//popup/index.css body { width: 500px; height: 500px; background-color: #eee; } form { padding: 20px; text-align: center; } dd { padding: 10px; }

5.输入扩展插件的地址,打开开发者模式,加载开发好的插件。

淘宝浏览器插件排行(浏览器插件开发)(2)

6.测试插件效果:

淘宝浏览器插件排行(浏览器插件开发)(3)

,