简体   繁体   English

打开一个新的Google Chrome标签并获取源

[英]Open a new Google Chrome tab and get the source

I'm developing a Google Chrome extension and I'd like to know how to open a new tab (ok, this is simple: chrome.tabs.create({'url': chrome.extension.getURL(mypage)}, function(tab) { /* ... */ }); ) and retrieve the source code of that page. 我正在开发Google Chrome扩展程序,我想知道如何打开一个新标签页(好吧,这很简单: chrome.tabs.create({'url': chrome.extension.getURL(mypage)}, function(tab) { /* ... */ }); )并检索该页面的源代码。

I know that I can use AJAX to get the source, but the problem is that the web page contains some Javascript code that edits the page, and I need the edited page. 我知道我可以使用AJAX来获取源代码,但是问题是网页包含一些Javascript代码来编辑页面,而我需要编辑后的页面。

Is it possible? 可能吗?

To serialize the full, live HTML document, use the following code: 要序列化完整的实时HTML文档,请使用以下代码:

// @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;
}

Now, in a Chrome extension, you have to add some events to the extension page such as a background page or popup page: 现在,在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.
    }
}

The above function returns the source code of the main frame in a tab. 上面的函数在选项卡中返回主框架的源代码。 If you want to get the source of a child frame, call chrome.tabs.executeScript with a frameId parameter. 如果要获取子框架的来源,请使用frameId参数调用chrome.tabs.executeScript

The next snippet shows an example of how your extension could use the function. 下一个代码片段显示了扩展程序如何使用该功能的示例。 Paste the snippet in the background page's console , or declare a browserAction , put the snippet in the onClicked listener and click on the extension button. 将代码段粘贴到后台页面的控制台中 ,或声明一个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);
});

The referenced get_source.js contains the following code: 引用的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);

Don't forget to add the appropriate host permissions , so that you can read DOM from the page. 不要忘记添加适当的主机权限 ,以便您可以从页面读取DOM。 In the above example, you have to add "https://example.com/*" to the "permissions" section of manifest.json. 在上面的示例中,您必须在manifest.json的“权限”部分中添加"https://example.com/*"

Related documentation 相关文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM