栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从Chrome扩展程序获取当前页面的源HTML

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从Chrome扩展程序获取当前页面的源HTML

将脚本插入您要从中获取源代码的页面中,并将其发送回弹出窗口…。

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)});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/670578.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号