微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 打开新的Google Chrome标签并获取来源

我正在开发Google Chrome扩展程序,我想知道如何打开新标签(好吧,这很简单:
chrome.tabs.create({‘url’:chrome.extension.getURL(mypage)},function(tab){/ * … * /});
)并检索该页面的源代码.

我知道我可以使用AJAX获取代码,但问题是网页包含一些编辑页面Javascript代码,我需要编辑的页面.

可能吗?

解决方法:

要序列化完整的实时HTML文档,请使用以下代码

// @author Rob W <https://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扩展程序中,您必须向扩展程序页面添加一些事件,例如后台页面或弹出页面

/**
 * Get the HTML source for the main frame of a given tab.
 *
 * @param {integer} tabId - ID of tab.
 * @param {function} callback - Called with the tab's source upon completion.
 */
function getSourceFromTab(tabId, callback) {
    // Capture the page when it has fully loaded.
    // When we kNow the tab, execute the content script
    chrome.tabs.onUpdated.addListener(onUpdated);
    chrome.tabs.onRemoved.addListener(onRemoved);
    function onUpdated(updatedTabId, details) {
        if (details.status == 'complete') {
            removeListeners();
            chrome.tabs.executeScript(tabId, {
                file: 'get_source.js'
            }, function(results) {
                // Todo: Detect injection error using chrome.runtime.lastError

                var source = results[0];
                done(source);
            });
        }
    }
    function removeListeners() {
        chrome.tabs.onUpdated.removeListener(onUpdated);
        chrome.tabs.onRemoved.removeListener(onRemoved);
    }

    function onRemoved() {
        removeListeners();
        callback(''); // Tab closed, no response.
    }
}

上面的函数返回选项卡中主框架的源代码.如果要获取子帧的源,请使用frameId参数调用chrome.tabs.executeScript.

一个代码显示了您的扩展程序如何使用该功能的示例.将片段粘贴到background page’s console中,或声明browserAction,将片段放入onClicked侦听器中,然后单击扩展按钮.

var mypage = 'https://example.com';
var callback = function(html_string) {
    console.log('HTML string, from extension: ', html_string);
};
chrome.tabs.create({
    url: mypage
}, function(tab) {
    getSourceFromTab(tab.id, callback);
});

引用的get_source.js包含以下代码

function DOMtoString(document_root) {
    ... see top of the answer...
}
// The value of the last expression of the content script is passed
// to the chrome.tabs.executeScript callback
DOMtoString(document);

不要忘记添加适当的host permissions,以便您可以从页面中读取DOM.在上面的示例中,您必须将“https://example.com/*”添加到manifest.json的“permissions”部分.

相关文档

> Node MDN
> DocumentType(document.doctype,<!DOCTYPE ...>)MDN
> Content scripts Google Chrome扩展程序文档
> Match patterns Google Chrome扩展程序文档
> Manifest > permissions Google Chrome扩展程序文档
> chrome.tabs.create Google Chrome扩展程序文档
> chrome.tabs.executeScript Google Chrome扩展程序文档
> chrome.tabs.onUpdated Google Chrome扩展程序文档
> chrome.tabs.onRemoved Google Chrome扩展程序文档
> Message passing Google Chrome扩展程序文档

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐