昨天想寫一個chrome爬蟲插件,我用jq試了一下,狀況是這樣的:javascript
var baseUrl = "http://www.example.com/"; function startFetch() { $.get(baseUrl, function (data) { var str = $('<div></div>').append(data).find('#id').html(); $('#log').html(str); }); } $(function () { $("#startFetch").bind("click", startFetch); });
一開始發現,$.get返回的數據是一個完整的html代碼,就像這樣:html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body></body></html>
我直接用$(data)獲得的是一個dom節點集合,而不是一個jq對象,stackoverflow上也有人問到這種狀況,綜合幾種狀況,我採用了$('<div></div>').append(data)
這個方案。用$('<div></div>')
這個實際不存在的節點來保存這個html文檔,而後append返回的就是我要的jq對象的形式。java
在用jq實現以後,我又用js從新寫了一個,具體以下:web
var baseUrl = "http://www.example.com/"; var get = request.bind(this, 'GET'); function startFetch() { get(baseUrl, function (data) { var newDiv, str; newDiv = document.createElement('div'); newDiv.innerHTML = data; //這裏若是改用appendChild就會報錯 str = newDiv.querySelectorAll('selector')[1].innerHTML; document.getElementById('log').innerHTML = str; }); } window.onload = function () { document.getElementById('startFetch').addEventListener('click', startFetch); }; function request(type, url, opts, callback) { var xhr = new XMLHttpRequest(); if (typeof opts === 'function') { callback = opts; opts = null; } xhr.open(type, url); var fd = new FormData(); if (type === 'POST' && opts) { for (var key in opts) { fd.append(key, JSON.stringify(opts[key])); } } xhr.onload = function () { callback(xhr.response); }; xhr.send(opts ? fd : null); }
如下是我完整的整個插件的結構:
|-js
|-popup.js
|-icon16.png
|-icon48.png
|-icon128.png
|-manifest.json
|-popup.htmlchrome
完整代碼以下:json
//popup.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #log { width: 200px; line-height: 20px; } </style> <script type="text/javascript" src="js/popup.js"></script> </head> <body> <button id="startFetch">獲取帳號密碼</button> <div id="log">獲取中......</div> </body> </html>
//manifest.json { "manifest_version": 2, "name": "更新ss", "description": "獲取免費帳號並更新到本地", "version": "1.0", "icons": { "16": "icon16.png", "48": "icon48.png", "128": "icon128.png" }, "browser_action": { "default_icon": "icon128.png", "default_popup": "popup.html" }, "permissions": [ "activeTab", "webRequest", "webNavigation", "webRequestBlocking", "proxy", "*://*/*" ] }
popup.js的代碼就是上面純js版app