开发Chrome插件,如抢票、秒杀、页面数据抓取等,能够搜集一些数据。javascript
开发插件须要的东西:manifest.json popup.html popup.js content-script.js background.jshtml
配置文件:manifest.jsonjava
{ "name": "webtrendsTool", "manifest_version": 2, "version": "1.0", "description": "chrome自制小插件", "background": { "scripts": ["zepto.js","background.js"] }, "page_action": { "default_icon": { "19": "ico.png", "38": "ico.png" }, "default_title": "webtrendsTool", // shown in tooltip "default_popup": "popup.html" }, "permissions": [ "tabs","http://localhost/"], "content_scripts": [ { "matches": ["https://www.cnblogs.com/*"], "js": ["zepto.js", "content-script.js"], "run_at":"document_end" } ] }
background script即插件运行的环境,这是chrome专门给插件开辟的一块地方,与页面的脚本分开,通常咱们browser级别的逻辑就会写在这里。web
content script: 就是能够对页面内容进行操做的脚本了,它能够访问DOM里的内容,但又受到不少限制,好比并不能访问web页面或其它content script中定义的函数和变量,它默认是在网页加载完了和页面脚本执行完了,页面转入空闲的状况下(Document Idle)就会运行,但这个是能够改变的。content script和咱们扩展的background script处于不一样的环境,它们须要之间经过message机制来进行通讯。个人理解是,content script其实算是插件与page操做交互的一个桥梁了。ajax
content script:其实算是插件与page操做交互的一个桥梁,这个里面主要是获取目标页面上的数据,能够操做目标页面的dom,好比从页面上抓取dom,解析数据。background: 浏览器级别的操做chrome
popup.js: 经过background 获取抓取的页面数据json
content-script.js浏览器
var msgData = []; console.log('content-script!!!!'); var allProducts = $(".post_item"); for(var i=0,len=allProducts.length;i<len;i++){ var name = allProducts.eq(i).find(".titlelnk").html(); var promoprice = allProducts.eq(i).find(".diggnum").html(); msgData.push({'name':name,'price':promoprice}); } //数据传递 与background.js通讯 chrome.runtime.sendMessage(msgData);
background.jsdom
function getDomainFromUrl(url){ var host = "null"; if(typeof url == "undefined" || null == url) url = window.location.href; var regex = /.*\:\/\/([^\/]*).*/; var match = url.match(regex); if(typeof match != "undefined" && null != match) host = match[1]; return host; } function checkForValidUrl(tabId, changeInfo, tab) { if(getDomainFromUrl(tab.url).toLowerCase()=="www.cnblogs.com"){ //只在指定页面展现 插件图片 chrome.pageAction.show(tabId); } }; chrome.tabs.onUpdated.addListener(checkForValidUrl); //接收从content-script传递来的数据,供popup使用 var postData = {}; chrome.runtime.onMessage.addListener(function(request, sender, sendRequest){ postData = request; // $.ajax({ // url: "http://localhost:3000/savedata", // cache: false, // type: "POST", // data: JSON.stringify(postData), // dataType: "json", // success:function(response){ // }, // error:function(err){ // } // }) });
popup.js函数
//background 里面的数据 document.addEventListener('DOMContentLoaded', function () { var data = chrome.extension.getBackgroundPage().postData || ''; console.log('popup---postData',data); $(".info").html(JSON.stringify(data)); });