将脚本插入您要从中获取源代码的页面中,并将其发送回弹出窗口…。
manifest.json
{ "name": "Get pages source", "version": "1.0", "manifest_version": 2, "description": "Get pages source from a popup", "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "permissions": ["tabs", "<all_urls>"]}popup.html
<!DOCTYPE html><html style=''><head><script src='popup.js'></script></head><body ><div id='message'>Injecting script....</div></body></html>
popup.js
chrome.runtime.onMessage.addListener(function(request, sender) { if (request.action == "getSource") { message.innerText = request.source; }});function onWindowLoad() { var message = document.querySelector('#message'); chrome.tabs.executescript(null, { file: "getPagesSource.js" }, function() { // If you try and inject into an extensions page or the webstore/NTP you'll get an error if (chrome.runtime.lastError) { message.innerText = 'There was an error injecting script : n' + chrome.runtime.lastError.message; } });}window.onload = onWindowLoad;getPagesSource.js
// @author Rob W <http://stackoverflow.com/users/938089/rob-w>// Demo: var serialized_html = DOMtoString(document);function DOMtoString(document_root) { var html = '', node = document_root.firstChild; while (node) { switch (node.nodeType) { case Node.ELEMENT_NODE: html += node.outerHTML; break; case Node.TEXT_NODE: html += node.nodevalue; break; case Node.CDATA_SECTION_NODE: html += '<![CDATA[' + node.nodevalue + ']]>'; break; case Node.COMMENT_NODE: html += '<!--' + node.nodevalue + '-->'; break; case Node.document_TYPE_NODE: // (X)HTML documents are identified by public identifiers html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>n'; break; } node = node.nextSibling; } return html;}chrome.runtime.sendMessage({ action: "getSource", source: DOMtoString(document)});


